RunKit + npm: joi

node v18.11.0
endpointsharetweet
const Joi = require("joi"); // episodes const episodeSchema = Joi.object({ id: Joi.string().required(), name: Joi.string(), }); // seasons const seasonSchema = Joi.object({ id: Joi.string().required(), seasonNumber: Joi.number(), episodes: Joi.array().items(episodeSchema).required(), }); const schema = Joi.object({ id: Joi.string().required(), format: Joi.string() .equal(...["movie", "series"]) .required(), status: Joi.string() .equal(...["fail", "pass"]) .required(), seasons: Joi.when("format", { is: "series", then: Joi.when("status", { is: "pass", then: Joi.array() .items( seasonSchema.concat(Joi.object({ episodes: Joi.array().min(5) })) ) .min(2) .required(), otherwise: Joi.array().items(seasonSchema).required(), }), otherwise: Joi.forbidden(), }), }); const tests = [ { id: "a", format: "series", status: "pass", seasons: [{ id: "b", episodes: [] }], }, { id: "a", format: "series", status: "fail", seasons: [{ id: "b", episodes: [] }], }, { id: "a", format: "series", status: "pass", seasons: [ { id: "b", episodes: Array.from({ length: 5 }, (v, i) => ({ id: i.toString(), name: i.toString(), })), }, ], }, { id: "a", format: "series", status: "pass", seasons: [ { id: "b", episodes: Array.from({ length: 5 }, (v, i) => ({ id: i.toString(), name: i.toString(), })), }, { id: "c", episodes: [] }, ], }, { id: "a", format: "series", status: "pass", seasons: [ { id: "b", episodes: Array.from({ length: 5 }, (v, i) => ({ id: i.toString(), name: i.toString(), })), }, { id: "c", episodes: Array.from({ length: 5 }, (v, i) => ({ id: i.toString(), name: i.toString(), })), }, ], }, { id: "a", format: "series", status: "fail", seasons: [ { id: "b", episodes: Array.from({ length: 5 }, (v, i) => ({ id: i.toString(), name: i.toString(), })), }, { id: "c", episodes: [] }, ], }, ]; for (const test of tests) { console.log(schema.validate(test)); }
Created from: https://npm.runkit.com/joi
Loading…