Joi: Ref will not be converted if it is inside array passed to default

Created on 8 Oct 2016  路  3Comments  路  Source: sideway/joi

Context

  • _node version_: 6.7.0
  • _joi version_: 9.1

    What are you trying to achieve or the steps to reproduce ?

const schema = Joi.object().keys({
  authors: Joi.array().items(Joi.string()).default([Joi.ref('$user')]),
});

This also will not work:

Joi.array().items(Joi.string()).default(Joi.ref(['$user']))
Joi.array().items(Joi.string()).default(Joi.ref('[$user]'))
Joi.array().items(Joi.string()).default(Joi.ref('$user')).single()

Which result you had ?

{authors: [null]}

What did you expect ?

{authors: ['defaultUser']}
bug

Most helpful comment

There was a missing piece in joi to let you accomplish that which is why I consider this a bug. But for obvious reasons, joi is not going to deep explore your objects looking for references, but you can generate those defaults using a function like :

const schema = Joi.object().keys({
    authors: Joi.array().items(Joi.string()).default(function (value, options) {
        return [Joi.ref('$user')(value, options)];
    }, 'Array with default user'),
});

All 3 comments

@farwayer I assume you are attempting to validate some object with the schema(s) mentioned above, could you please provide some examples of your input data.

It was just example, but sure I can provide data that will fail:

const schema = Joi.object().keys({
  authors: Joi.array().items(Joi.string()).default([Joi.ref('$user')]),
});

const data = {};

const {value} = Joi.validate(data, schema, {context: {user: 'defaultUser'}})

// values should be {authors: ['defaultUser']}
// but will be {authors: [null]}

There was a missing piece in joi to let you accomplish that which is why I consider this a bug. But for obvious reasons, joi is not going to deep explore your objects looking for references, but you can generate those defaults using a function like :

const schema = Joi.object().keys({
    authors: Joi.array().items(Joi.string()).default(function (value, options) {
        return [Joi.ref('$user')(value, options)];
    }, 'Array with default user'),
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

a-c-m picture a-c-m  路  3Comments

JbIPS picture JbIPS  路  4Comments

normancarcamo picture normancarcamo  路  3Comments

kailashyogeshwar85 picture kailashyogeshwar85  路  4Comments

Taxi4you picture Taxi4you  路  3Comments