UNPKG

@benshi.ai/js-sdk

Version:

Benshi SDK

49 lines (38 loc) 1.45 kB
export const checkSchema = (schema, message) => { // check first level fields (main_ingest_body) // all of them are mandatory const messageFirstLevelFields = Object.keys(message) const typeMappings = { 'int': 'number', 'string': 'string', 'boolean': 'boolean', 'object': 'object' } for (let field of Object.keys(schema.main_ingest_body)) { if (field === 'required') { continue } if (field === 'ip') { // pending to discuss where the IP is ingested, in the SDK // or the server continue } const requiredFields = new Set(schema.main_ingest_body.required) if (message[field] === undefined && requiredFields.has(field)) { throw new Error('schema-validation-missing-field') } if (typeof (message[field]) !== typeMappings[schema.main_ingest_body[field].type]) { throw new Error('schema-validation-type-missmatch') } if (schema.main_ingest_body[field].enum !== undefined) { if (!schema.main_ingest_body[field].enum.includes(message[field])) { throw new Error('schema-validation-invalid-value') } } } for (let field of Object.keys(message)) { if (schema.main_ingest_body[field] === undefined) { throw new Error('schema-validation-extra-field') } } }