UNPKG

@tvkitchen/countertop

Version:

The entry point for developers who want to set up a TV Kitchen.

100 lines (99 loc) 2.92 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Payload = void 0; const avsc_1 = __importDefault(require("avsc")); const ajv_1 = require("../tools/ajv"); const types_1 = require("../types"); const errors_1 = require("../errors"); const jsonDeserializedBufferSchema = { type: 'object', properties: { type: { type: 'string', pattern: 'Buffer', }, data: { type: 'array', items: { type: 'integer', }, }, }, required: [ 'type', 'data', ], }; const isJsonDeserializedBuffer = ajv_1.ajv.compile(jsonDeserializedBufferSchema); class Payload { constructor(parameters) { this.data = parameters.data; this.type = parameters.type; this.createdAt = parameters.createdAt ?? (new Date()).toISOString(); this.origin = parameters.origin; this.duration = parameters.duration; this.position = parameters.position; } static serialize(payload) { return JSON.stringify(payload); } static deserialize(serializedPayload) { const deserializedPayload = JSON.parse(serializedPayload, (_, value) => { if (isJsonDeserializedBuffer(value)) { return Buffer.from(value.data); } return value; }); if ((0, types_1.isPayloadParameters)(deserializedPayload)) { return new Payload(deserializedPayload); } throw new errors_1.ValidationError('Invalid payload serialization', types_1.isPayloadParameters.errors); } static getAvroType() { return Payload.avroType; } static byteSerialize(payload) { return Payload.getAvroType().toBuffer(payload); } static byteDeserialize(serializedPayload) { const deserializedPayload = Payload.getAvroType().fromBuffer(serializedPayload); if ((0, types_1.isPayloadParameters)(deserializedPayload)) { return new Payload(deserializedPayload); } throw new Error('TV Kitchen defined a Avro Type which deserialized to an invalid Payload.'); } } exports.Payload = Payload; Payload.avroType = avsc_1.default.Type.forSchema({ name: 'Payload', type: 'record', fields: [ { name: 'data', type: 'bytes', }, { name: 'type', type: 'string', }, { name: 'createdAt', type: 'string', }, { name: 'origin', type: 'string', }, { name: 'duration', type: 'long', }, { name: 'position', type: 'long', }, ], });