Skip to content

Single and list of data auto-handling #313

@DenisFerrero

Description

@DenisFerrero

Hi, in my projects I handle many params as an array and they can be passed as a single value or as a list of values, but every time I have to manage this case manually

For example:

const Validator = require("fastest-validator");

const schema = {
    name: { type: 'multi', rules: [{ type: 'string' }, { type: 'array', items: 'string' }] }
};

const check = (new Validator()).compile(schema);

const params = { name: 'John' }

check(params);
if (params.name && !Array.isArray(params.name)) params.name = [params.name];

const query = `SELECT * FROM users WHERE name IN (${params.name.join(', ')})`

It would be great if this array conversion could be done directly by the validator using a parameter. For example:

const Validator = require("fastest-validator");

// By running an array validation with the wrap: true property the param even if it's a string it's wrapped inside an array before running the validation
const schema = {
    name: { type: 'array', items: 'string', wrap: true }
};

const check = (new Validator()).compile(schema);

const params = { name: 'John' }

check(params);
// params.name now is equal to ['John']

const query = `SELECT * FROM users WHERE name IN (${params.name.map(name => `'${name}'`).join(', ')})`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions