Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In hapi/joi. How can I combine 2 different schema validations in one?

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?

like image 309
Reacting Avatar asked Oct 18 '25 08:10

Reacting


1 Answers

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); //?
like image 159
Denis Tsoi Avatar answered Oct 19 '25 20:10

Denis Tsoi