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

support dynamic defaults via registered callback functions #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

eldridge
Copy link

@eldridge eldridge commented Aug 28, 2019

Thank you for joi-json. This package is a missing piece of functionality to joi, in my humble opinion. The ability to define validation in data structures instead of raw code is a key draw to joi/joi-json.

Unfortunately, there are a few things that joi can do that joi-json cannot. This PR adds support for dynamic defaults by registering callback functions with the parser that can be invoked if a string is supplied as a default that contains enclosing parentheses.

For example, if we had a list of Express routes with separate validation profiles:

[
    {
        method: "SEARCH",
        url: "/author",
        validation: {
            page_size: "number:integer,min=1,max=1000,default=50"
        }
    },
    {
        method: "SEARCH",
        url: "/publication",
        validation: {
            page_size: "number:integer,min=1,max=1000,default=50"
        }
    }
]

What if we wanted "50" to be a global default defined in a central configuration using the config package, we could define a callback that would pull it from a global configuration:

const lodash = require("lodash");
const config = require("config");
const joijson = require("joi-json").builder();

joijson.registerFunction("config", path => lodash.get(config, path));

const schema = joijson.build({
    page_size: "number:integer,min=1,max=1000,default=config(app.default_page_size)"
});

Pretty powerful, yeah?

@richardhyatt
Copy link
Contributor

I like it - could we extend the scope larger than just default values? Could we use a similar syntax to specify a set of properties that could be returned from the function to allow a more dynamic way to define more of the mundane validation properties? Should we also look at adding functionality like lodash's get() to make it easy to define path based values?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants