Skip to content

Commit

Permalink
feat(Date): Add support for serializing and deserializing date type
Browse files Browse the repository at this point in the history
Fixes #362
  • Loading branch information
Belphemur committed Aug 8, 2022
1 parent dbb3b7b commit e62e792
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/adapter/data/JsonAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,40 @@ export class JsonAdapter implements IAdapter<any> {

private readonly adapter: IAdapter<string>;
private readonly humanReadable: boolean;
private readonly dateRegex = new RegExp('^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}', 'm')


constructor(adapter: IAdapter<string>, humanReadable: boolean = false) {
this.adapter = adapter;
this.humanReadable = humanReadable;
}

private replacer(key: string, value: any): any {
return value;
}

private reviver(key: string, value: any): any {
if (typeof value == "string" && this.dateRegex.exec(value) != null) {
return new Date(value);
}
return value;
}

async readAsync(): Promise<any> {
const data = await this.adapter.readAsync();
if (data == null) {
await this.writeAsync({});
return {};
}
return JSON.parse(data);
return JSON.parse(data, this.reviver.bind(this));
}

writeAsync(data: any): Promise<void> {
let stringify = '';
if (this.humanReadable) {
stringify = JSON.stringify(data, null, 4)
stringify = JSON.stringify(data, this.replacer.bind(this), 4)
} else {
stringify = JSON.stringify(data)
stringify = JSON.stringify(data, this.replacer.bind(this))
}
return this.adapter.writeAsync(stringify);
}
Expand Down
13 changes: 13 additions & 0 deletions test/adapter/adapters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,19 @@ describe('Adapter', () => {
expect(fileExists).toBeTruthy();

})

test('should serialize and deserialize dates', async () => {
const adapter = new JsonAdapter(new MemoryAdapter(), false);
const data = {
myDate: new Date()
}

await adapter.writeAsync(data);
const readObject = await adapter.readAsync();
expect(readObject).not.toBeNaN();
expect(readObject.myDate).toBeInstanceOf(Date);
expect(readObject.myDate.toString()).toBe(data.myDate.toString())
})
})
});
describe('Config', () => {
Expand Down

0 comments on commit e62e792

Please sign in to comment.