Skip to content

Commit

Permalink
fix: handle unexpected date type reflection
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamin658 committed Apr 15, 2021
1 parent 28f35cb commit 8124221
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,26 @@ export function encodeByType(type: string, value: any): string | null {
case 'string': {
return encodeURIComponent(value);
}
default: {
throw new Error(`unknown type in cursor: [${type}]${value}`);
case 'object': {
/**
* if reflection type is Object, check whether an object is a date.
* see: https://github.com/rbuckton/reflect-metadata/issues/84
*/
if (typeof value.getTime === 'function') {
return (value as Date).getTime().toString();
}

break;
}
default: break;
}

throw new Error(`unknown type in cursor: [${type}]${value}`);
}

export function decodeByType(type: string, value: string): string | number | Date {
switch (type) {
case 'object':
case 'date': {
const timestamp = parseInt(value, 10);

Expand Down
19 changes: 19 additions & 0 deletions test/reflection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { expect } from 'chai';

import { encodeByType, decodeByType } from '../src/utils';

describe('Reflect.getMetadata Date type is Object test', () => {
it('should encode cursor correctly with object type and date value', () => {
const date = new Date();
const encoded = encodeByType('object', date);

expect(encoded).to.be.a('string');
});

it('should decode cursor correctly with object type and date string value', () => {
const value = new Date().getTime().toString();
const decoded = decodeByType('object', value);

expect(decoded).to.be.a('date');
});
});

0 comments on commit 8124221

Please sign in to comment.