Skip to content

Commit 22454da

Browse files
committed
(de)serialize dates w/ ISO8601
1 parent 318af54 commit 22454da

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

packages/functions/src/serializer.ts

+11
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ export class Serializer {
5151
if (data === true || data === false) {
5252
return data;
5353
}
54+
if (data instanceof Date) {
55+
return data.toISOString();
56+
}
5457
if (Object.prototype.toString.call(data) === '[object String]') {
5558
return data;
5659
}
@@ -95,6 +98,14 @@ export class Serializer {
9598
if (typeof json === 'function' || typeof json === 'object') {
9699
return mapValues(json!, x => this.decode(x));
97100
}
101+
if (
102+
typeof json === 'string' &&
103+
/^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$/.test(
104+
json
105+
)
106+
) {
107+
return new Date(json);
108+
}
98109
// Anything else is safe to return.
99110
return json;
100111
}

packages/functions/test/serializer.test.ts

+12
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,18 @@ describe('Serializer', () => {
8080
expect(serializer.decode(1.2)).to.equal(1.2);
8181
});
8282

83+
it('encodes date', () => {
84+
expect(serializer.encode(new Date('2021-02-10T13:26:37.977Z'))).to.equal(
85+
'2021-02-10T13:26:37.977Z'
86+
);
87+
});
88+
89+
it('decodes date', () => {
90+
expect(serializer.decode('2021-02-10T13:26:37.977Z')).to.deep.equal(
91+
new Date('2021-02-10T13:26:37.977Z')
92+
);
93+
});
94+
8395
it('encodes string', () => {
8496
expect(serializer.encode('hello')).to.equal('hello');
8597
});

0 commit comments

Comments
 (0)