UNPKG

node-test-bed-adapter

Version:

An adapter to connect a node.js application to the Test-bed's Common Information Space or Common Simulation Space.

47 lines 2.15 kB
import { toMessageBuffer, fromMessageBuffer } from './../models/magic-byte.mjs'; import { Logger } from '../logger/index.mjs'; // const removeNulls = (_key: string, value: any) => // value === 'null' || value === null ? undefined : value; /** * Create an object that knows how to validate/encode/decode keys and values of a message. * * @param sr Schema registry * @param topic Topic to publish to. Is also the key to retreive schema's for key/value */ export const avroHelperFactory = (sr, topic) => { const log = Logger.instance; const valueSchema = sr.valueSchemas[topic] || sr.valueSchemas[topic + '-value']; const keySchema = sr.keySchemas[topic] || sr.keySchemas[topic + '-key']; const errorHook = (path, part) => log.error(`avroHelperFactory() - Topic ${topic}, path ${path.join(', ')} ${JSON.stringify(part, null, 2)}`); return { /** Check whether the message is valid */ isValid: (messages) => messages.every((m) => valueSchema.type.isValid(m.value, { errorHook }) && (!keySchema || m.key instanceof Buffer || keySchema.type.isValid(m.key, { errorHook }))), /** Check whether the message is valid */ isValidKey: (key) => !keySchema || keySchema.type.isValid(key, { errorHook }), /** Encode the message or messages */ encode: (m) => ({ ...m, value: toMessageBuffer(m.value, valueSchema.type, valueSchema.srId), key: m.key ? m.key instanceof Buffer ? m.key : toMessageBuffer(m.key, keySchema.type, keySchema.srId) : undefined, }), encodeKey: (key) => keySchema ? toMessageBuffer(key, keySchema.type, keySchema.srId) : undefined, /** Decode the buffer */ decode: (m) => ({ value: fromMessageBuffer(valueSchema.type, m.value, sr).value, key: m.key && keySchema ? fromMessageBuffer(keySchema.type, m.key, sr).value : undefined, }), }; }; //# sourceMappingURL=avro-helper-factory.mjs.map