Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ref will not be converted if it is inside array passed to default #1002

Closed
farwayer opened this issue Oct 8, 2016 · 3 comments
Closed

Ref will not be converted if it is inside array passed to default #1002

farwayer opened this issue Oct 8, 2016 · 3 comments
Assignees
Labels
bug Bug or defect
Milestone

Comments

@farwayer
Copy link

farwayer commented Oct 8, 2016

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']}
@DavidTPate
Copy link
Contributor

@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.

@farwayer
Copy link
Author

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]}

@Marsup Marsup added the bug Bug or defect label Oct 12, 2016
@Marsup Marsup self-assigned this Oct 12, 2016
@Marsup Marsup closed this as completed in 30d1147 Oct 12, 2016
@Marsup Marsup added this to the 9.1.1 milestone Oct 12, 2016
@Marsup
Copy link
Collaborator

Marsup commented Oct 12, 2016

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'),
});

@lock lock bot locked as resolved and limited conversation to collaborators Jan 10, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Bug or defect
Projects
None yet
Development

No branches or pull requests

3 participants