diff --git a/src/classes/Payload.ts b/src/classes/Payload.ts index 8bf2037..ac940c3 100644 --- a/src/classes/Payload.ts +++ b/src/classes/Payload.ts @@ -1,4 +1,7 @@ +import { ajv } from '../tools/ajv' import { isPayloadParameters } from '../types' +import { ValidationError } from '../errors' +import type { JSONSchemaType } from 'ajv' import type { PayloadParameters, PayloadType, @@ -6,13 +9,28 @@ import type { interface JsonDeserializedBuffer { type: string; - data: string; + data: number[]; } -const isJsonDeserializedBuffer = (value: unknown): value is JsonDeserializedBuffer => ( - value instanceof Object - && 'type' in value - && 'data' in value -) +const jsonDeserializedBufferSchema: JSONSchemaType = { + type: 'object', + properties: { + type: { + type: 'string', + pattern: 'Buffer', + }, + data: { + type: 'array', + items: { + type: 'integer', + }, + }, + }, + required: [ + 'type', + 'data', + ], +} +const isJsonDeserializedBuffer = ajv.compile(jsonDeserializedBufferSchema) export class Payload { public readonly data: Buffer @@ -42,8 +60,7 @@ export class Payload { public static deserialize(serializedPayload: string): Payload { const deserializedPayload: unknown = JSON.parse(serializedPayload, (_, value: unknown) => { - if (isJsonDeserializedBuffer(value) - && value.type === 'Buffer') { + if (isJsonDeserializedBuffer(value)) { return Buffer.from(value.data) } return value @@ -51,6 +68,10 @@ export class Payload { if (isPayloadParameters(deserializedPayload)) { return new Payload(deserializedPayload) } - throw new Error(`Invalid payload serialiation: ${serializedPayload}`) + + throw new ValidationError( + 'Invalid payload serialiation', + isPayloadParameters.errors, + ) } } diff --git a/src/classes/__test__/Payload.unit.test.ts b/src/classes/__test__/Payload.unit.test.ts index f001fdc..5776db3 100644 --- a/src/classes/__test__/Payload.unit.test.ts +++ b/src/classes/__test__/Payload.unit.test.ts @@ -1,3 +1,4 @@ +import { ValidationError } from '../../errors' import { Payload } from '../Payload' describe('Payload', () => { @@ -71,10 +72,10 @@ describe('Payload', () => { describe('deserialize', () => { it('should error when deserializing an empty serialized object', () => { - expect(() => Payload.deserialize('{}')).toThrow() + expect(() => Payload.deserialize('{}')).toThrow(ValidationError) }) it('should error when deserializeing a partially populated serialized payload', () => { - expect(() => Payload.deserialize('{"type":"WHOOPS"}')).toThrow() + expect(() => Payload.deserialize('{"type":"WHOOPS"}')).toThrow(ValidationError) }) it('should properly deserialize a serialized payload', () => { const parameters = { @@ -100,7 +101,7 @@ describe('Payload', () => { position: 60000, } const serializedValues = JSON.stringify(parameters) - expect(() => Payload.deserialize(serializedValues)).toThrow() + expect(() => Payload.deserialize(serializedValues)).toThrow(ValidationError) }) }) })