Joi schema: dynamic allow/items validation - "Method no longer accepts array arguments"

57 Views Asked by At

I have the need to "extend"/use the schema.items()/schema.allow() with a array, where items can be added.

const Joi = require("joi");


const allow = ["foo", "bar"];

const schema = Joi.array().valid(allow);


allow.push("baz");

const {error, value} = schema.validate(["baz"]);


console.log(error || value);

The problem is, items()/allow() do not allow a array as parameter, and using the spread operator does not work.

/home/marc/projects/playground/node_modules/@hapi/hoek/lib/assert.js:21
    throw new AssertError(args);
    ^

Error: Method no longer accepts array arguments: valid
    at new module.exports (/home/marc/projects/playground/node_modules/@hapi/hoek/lib/error.js:23:19)
    at module.exports (/home/marc/projects/playground/node_modules/@hapi/hoek/lib/assert.js:21:11)
    at exports.verifyFlat (/home/marc/projects/playground/node_modules/joi/lib/common.js:214:9)
    at internals.Base.valid (/home/marc/projects/playground/node_modules/joi/lib/base.js:297:16)
    at Object.<anonymous> (/home/marc/projects/playground/joi-dynamic-items/index.js:6:28)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)

Node.js v20.11.0

How can i add allowed items to the array that joi picks up the newly added allowed items?

1

There are 1 best solutions below

0
Yanis Bendahmane On

Did you consider not using an array ?

const schema = Joi.array().valid("foo", "bar");

If you check into the lib, valid uses a spread operator

valid(...values: any[]): this;

If you still consider using an array, doing this can also be a solution

const allow = ["foo", "bar"];

const schema = Joi.array().valid(allow.join(","));

About the issue of adding dynamically a key to the schema, I might think it's not possible. A schema is basically, a snapshot of the object you wish to check in time, making it mutable would make it loose it's main usage. Instead of doing changes after the schema initialization, consider making your dynamic array before initializing your schema.