Joi: Dynamic Schema Generation

Created on 16 Mar 2014  路  6Comments  路  Source: sideway/joi

This could be implemented outside of the core, but it would be nice to have a standard JSON format to create joi schemas on the fly.

Use case:
Say a client wants to define a new data type with validation. JSON interpretation would allow both the data and the schema to be saved in the db.

feature

Most helpful comment

See #1867

All 6 comments

Sounds like a fun project. I agree it doesn't belong in joi itself. I don't have any use cases for this but if someone comes with one, I'm happy to reopen the issue.

If anyone stumbles across this, I have the exact same use case as OP describes. I have solved it using eval - granted - not pretty, but works very well.

const schemaObject = {};
if (type === 'string' ) {
    joiSchemaDescription += 'Joi.string()';
    if (min_length) {
        joiSchemaDescription += '.min(min_length)';
    }
    if (max_length) {
        joiSchemaDescription += '.max(max_length)';
    }
    if (required) {
        joiSchemaDescription += '.required()';
    }
    schemaObject[name] = eval(`${joiSchemaDescription};`);
}
// 'name' is also provided by the user, so you end up with a nice custom Schema like:
// schemaObject = {
//     someName: Joi.string().min(5).required(),
//     someOtherName: Joi.number().required();
// };
// Then validate like this:
// const fullSchema = Joi.object().keys(schemaObject);
// const validation = Joi.validate(data, fullSchema);

If anyone stumbles across this, I have the exact same use case as OP describes. I have solved it using eval - granted - not pretty, but works very well.

const schemaObject = {};
if (type === 'string' ) {
  joiSchemaDescription += 'Joi.string()';
  if (min_length) {
      joiSchemaDescription += '.min(min_length)';
  }
  if (max_length) {
      joiSchemaDescription += '.max(max_length)';
  }
  if (required) {
      joiSchemaDescription += '.required()';
  }
  schemaObject[name] = eval(`${joiSchemaDescription};`);
}
// 'name' is also provided by the user, so you end up with a nice custom Schema like:
// schemaObject = {
//     someName: Joi.string().min(5).required(),
//     someOtherName: Joi.number().required();
// };
// Then validate like this:
// const fullSchema = Joi.object().keys(schemaObject);
// const validation = Joi.validate(data, fullSchema);

Why we need eval (evil) here? Joi is chainable.

@hueniverse I'd like to pick this back up, how best to go about it? A new project? A PR?

Thanks!

See #1867

This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

neroaugustus1 picture neroaugustus1  路  4Comments

kailashyogeshwar85 picture kailashyogeshwar85  路  4Comments

chrisegner picture chrisegner  路  4Comments

PaunPrashant picture PaunPrashant  路  3Comments

n-sviridenko picture n-sviridenko  路  3Comments