Is there a way to validate the result of JSON.parse for different possible types? In the APIs I'm working on, various Json fields from the database need to have specific structures. I want to check if a certain JsonValue returned from the database is coherent with a given type.
I've experimented with different approaches. Here is how I defined the generic function:
parseJsonField<T>(jsonValue: Prisma.JsonValue): T {
return JSON.parse(JSON.stringify(jsonValue));
}
I am looking for a solution that throws an error when the jsonValue does not match the exact properties of type T, but this approach is not successful.
I am testing using this class:
export class ProgramTagsDTO {
key: string;
value: string;
constructor(key: string, value: string) {
this.key = key;
this.value = value;
}
}
Running the following test:
it('should validate', () => {
const tags: Prisma.JsonValue = [
{
key: 'key1',
value: 'value1',
wrongField: 'value',
},
{
key: 'key2',
value: 'value2',
},
];
let result = null;
const expectedResult = [
new ProgramTagsDTO('key1', 'value1'),
new ProgramTagsDTO('key2', 'value2'),
];
try {
result = programmesService.parseJsonField<ProgramTagsDTO[]>(tags);
} catch (error) {
expect(error).toBeInstanceOf(Error);
}
expect(result).toEqual(expectedResult);
});
The current outcome is:
expect(received).toEqual(expected) // deep equality
- Expected - 2
+ Received + 3
Array [
- ProgramTagsDTO {
+ Object {
"key": "key1",
"value": "value1",
+ "wrongField": "value",
},
- ProgramTagsDTO {
+ Object {
"key": "key2",
"value": "value2",
},
]
However, I want the method to throw an exception instead. The expect.toEqual is used just for logging purposes.