Skip to content

Commit

Permalink
Add "allowOverride" option to Jsonthis.registerGlobalSerializer() (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidecaroselli authored Apr 27, 2024
1 parent fcb0882 commit e922c9c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
23 changes: 23 additions & 0 deletions src/jsonthis.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,29 @@ describe("Jsonthis class", () => {
expect(() => jsonthis.registerGlobalSerializer(Date, dateSerializer))
.toThrow("Serializer already registered for \"Date\"");
});

it("should override a global serializer for a class if the override option is set", () => {
function overridingDateSerializer(value: Date): string {
return value.toUTCString();
}

class User {
public registeredAt: Date = new Date();
}
const user = new User();

const jsonthis = new Jsonthis();

jsonthis.registerGlobalSerializer(Date, dateSerializer);
expect(jsonthis.toJson(user)).toStrictEqual({
registeredAt: user.registeredAt.toISOString()
});

jsonthis.registerGlobalSerializer(Date, overridingDateSerializer, true);
expect(jsonthis.toJson(user)).toStrictEqual({
registeredAt: user.registeredAt.toUTCString()
});
});
});

describe("toJson method", () => {
Expand Down
5 changes: 3 additions & 2 deletions src/jsonthis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,10 @@ export class Jsonthis {
* Register a global serializer for a class.
* @param target The class to register the serializer for.
* @param serializer The serializer function.
* @param allowOverride Whether to allow overriding an existing serializer (default is false).
*/
registerGlobalSerializer(target: Function, serializer: JsonTraversalFn<any>): void {
if (this.serializers.has(target))
registerGlobalSerializer(target: Function, serializer: JsonTraversalFn<any>, allowOverride: boolean = false): void {
if (this.serializers.has(target) && !allowOverride)
throw new Error(`Serializer already registered for "${target.name}"`);
this.serializers.set(target, serializer);
}
Expand Down

0 comments on commit e922c9c

Please sign in to comment.