This is what I am doing:
import Joi, { AnySchema } from '@hapi/joi';
export const apiExtraInfo = (): AnySchema => {
return Joi.object({
message: Joi.string(),
apiVersion: Joi.string()
});
};
export const normalizeContentSchema = (): AnySchema => {
return Joi.object({
...apiExtraInfo(),
facets: Joi.object(),
count: Joi.number().required(),
content: Joi.array().items(Joi.object()).required()
});
};
The schema apiExtraInfo is going to be used across lots of different schemas so I don't want to be repeating myself.
The way I am doing it makes my schema to fail.
https://hapi.dev/module/joi/
Any suggestions?
Separate the api_schema and the object that makes up the api_schema (defined below as api_schema_definition).
This is because Joi schema only accepts plain objects.
(Tested using quokka.js)
const Joi = require("@hapi/joi");
const test_api_ok = {
message: "hello",
apiVersion: "any",
};
const test_normalize = {
message: "hello",
apiVersion: "any",
facets: {},
count: 1,
content: [{}],
};
const api_schema_definition = () => ({
message: Joi.string(),
apiVersion: Joi.string(),
});
const api_schema = Joi.object({
...api_schema_definition(),
});
const joined_schema = Joi.object({
...api_schema_definition(),
facets: Joi.object(),
count: Joi.number().required(),
content: Joi.array().items(Joi.object()).required(),
});
joined_schema.validate(test_normalize); //?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With