UNPKG

@bonniernews/abbe-api-utils

Version:

Utilities for converting to Abbe article format

48 lines (47 loc) 1.89 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateArticleSchema = void 0; const ajv_1 = __importDefault(require("ajv")); const ajv_formats_1 = __importDefault(require("ajv-formats")); let schema; const validateArticleSchema = async (article, abbeUrl) => { const validator = await getValidator(abbeUrl); if (!validator(article)) { if (validator.errors.length === 1 && isIgnorablePuffError(validator.errors[0])) return; throw new Error(`Validation failed ${JSON.stringify(validator.errors, null, 2)}`); } }; exports.validateArticleSchema = validateArticleSchema; /** * Schema says that puff must have an image but that is not required in the API. */ const isIgnorablePuffError = (error) => error.instancePath === "/puff/image" && error.schemaPath === "#/definitions/RelationByUuidIDTO/type" && error.message === "must be object"; async function getValidator(abbeUrl) { if (!schema) { schema = await fetchSchema(abbeUrl); } const ajv = new ajv_1.default({ allErrors: true, strict: true }); (0, ajv_formats_1.default)(ajv); ajv.addSchema(schema, "swagger"); const modelName = "ImportArticleIDTO"; const modelSchema = { $ref: "swagger#/definitions/" + modelName }; return ajv.compile(modelSchema); } async function fetchSchema(abbeUrl) { const res = await fetch(`${abbeUrl}/api/swagger.json`); if (!res.ok) { throw new Error("Failed to fetch Abbe JSON schema"); } const swaggerSchema = await res.json(); const spec = { definitions: swaggerSchema.definitions, }; Object.values(spec.definitions).forEach((definition) => (definition.additionalProperties = false)); return spec; }