Handle Date objects in compress util (#15547)

This commit is contained in:
Azri Kahar
2022-09-14 01:41:17 +08:00
committed by GitHub
parent c0e12638c6
commit 9b24233aa4
2 changed files with 36 additions and 0 deletions

View File

@@ -36,6 +36,14 @@ const geoJSON = {
],
};
const dateString = '2022-02-14T01:02:11.000Z';
const dateInput = {
date_created: new Date(dateString),
};
const dateOutput = {
date_created: dateString,
};
describe('compress', () => {
test('Compresses plain objects', () => {
expect(compress(plain)).toBe(
@@ -61,6 +69,10 @@ describe('compress', () => {
);
});
test('Compresses Date objects into strings', () => {
expect(compress(dateInput)).toBe('date_created|2022-02-14T01:02:11.000Z^^^$0|1]');
});
test('Throws error on non-supported types', () => {
expect(() => compress({ method: () => true })).toThrowError();
});
@@ -99,6 +111,10 @@ describe('decompress', () => {
).toEqual(geoJSON);
});
test('Decompresses Date strings', () => {
expect(decompress('date_created|2022-02-14T01:02:11.000Z^^^$0|1]')).toEqual(dateOutput);
});
test('Errors when not enough parts exist', () => {
expect(() => decompress('a|b^1K6^')).toThrowError();
});

View File

@@ -51,6 +51,26 @@ export function compress(obj: Record<string, any> | Record<string, any>[]) {
return ['@', ...part.map((subPart) => getAst(subPart))];
}
if (part instanceof Date) {
const value = encode(part.toJSON());
if (strings.has(value)) {
return {
type: Types.STRING,
index: strings.get(value)!,
};
}
const index = strings.size;
strings.set(value, index);
return {
type: Types.STRING,
index,
};
}
if (typeof part === 'object') {
return [
'$',