How to use the joi.validate function in joi

To help you get started, we’ve selected a few joi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github synapsestudios / oidc-platform / api / src / lib / validator / mixed-validation.js View on Github external
return (values, options, next) => {
    const schema = Joi.object().keys(joiSchema);
    options.context.values = values;

    return Joi.validate(values, schema, options, (errors, value) => {
      if (errors && options.abortEarly) {
        next(errors, value);
      } else if (! errors) {
        errors = new Error();
        errors.details = [];
      }

      return Promise.all(
        Object.keys(customSchema).map((path) => {
          if (! value[path]) {
            return;
          }

          return customSchema[path](value[path], options, next).catch(
            (err)   => {
              if (err.name !== 'ValidationError') { // A real error happened
github salesforce / refocus / db / helpers / botUtils.js View on Github external
function arrayHasValidParameters(arr) {
  if (arr === null || arr === undefined) {
    return;
  }

  const result = Joi.validate(arr, parameterArraySchema);

  if (result.error !== null) {
    throw new ValidationError({
      message: result.error.details,
    });
  }
} // arrayHasValidParameters
github xilution / xilution-react-todomvc / test / unit / backend / schemas.spec.js View on Github external
test('when the request is valid, the result should not include a validation error', () => {
      const actualValidationResult = Joi.validate({
        body: {
          completed: chance.bool(),
          text: chance.string(),
          userId: chance.string(),
        },
        parameters: {
          authorization: chance.string(),
        },
      }, postTodoRequestSchema);

      expect(actualValidationResult.error).toBeFalsy();
    });
  });
github tschwecke / harvey / lib / schemaValidator.js View on Github external
throw new Error('The following setup and teardown ids are specified more than once: \'' + duplicateIds.join('\', \'') + '\'');
			}

			//Make sure that if there is a teardown specified in a setup that it exists
			for(var i=0; i
github ArkEcosystem / core / packages / core-json-rpc / src / server / services / processor.ts View on Github external
public async resource(server, payload) {
        const { error } = Joi.validate(payload || {}, {
            jsonrpc: Joi.string()
                .valid("2.0")
                .required(),
            method: Joi.string().required(),
            id: Joi.required(),
            params: Joi.object(),
        });

        if (error) {
            return this.createErrorResponse(payload ? payload.id : null, -32600, error);
        }

        const { method, params, id } = payload;

        try {
            const targetMethod = get(server.methods, method);
github Paratii-Video / paratii-js / src / paratii.eth.vids.js View on Github external
async sendLike (options) {
    const schema = joi.object({
      videoId: joi.string().required(),
      liked: joi.bool().required()
    })

    const result = joi.validate(options, schema)
    const error = result.error
    if (error) throw error
    options = result.value

    if (options.liked !== true && options.liked !== false) {
      let msg = 'The liked argument should be a boolean'
      throw Error(msg)
    }
    let contract = await this.getVideoRegistry()
    let contract2 = await this.getLikesContract()

    let videoInfo = await contract.methods.get(options.videoId).call()

    if (videoInfo[0] === NULL_ADDRESS) {
      let msg = `Video with ID '${options.videoId}' doesn't exist`
      throw Error(msg)
github trailsjs / trailpack-waterline / lib / validator.js View on Github external
return new Promise((resolve, reject) => {
      joi.validate(config, lib.Schemas.databaseConfig, (err, value) => {
        if (err) return reject(err)

        return resolve(value)
      })
    })
  }
github jarontai / express-vue-admin / controller / admin / user.js View on Github external
update(req, res) {
    if (!req.params || !req.params.id) {
      return res.replyError('missing id parameter');
    }
    const rules = {
      username: joi.string().min(3),
      password: joi.string().min(6),
      disabled: joi.boolean(),
      roles: joi.array(),
    };
    const { error, value } = joi.validate(req.body, rules);
    if (error) {
      return res.replyError(error);
    }

    let updateRoles;
    const AdminRole = this.models['AdminRole'];
    const result = Promise.resolve().then(() => {
      if (value.password) {
        return pw.hash(value.password).then((hash) => {
          value.password = hash;
        });
      }
    }).then(() => {
      if (value.roles) {
        return AdminRole.findAll({ where: { name: value.roles } }).then((roles) => {
          updateRoles = roles;
github muraljs / joiql / lib / map-field-asts.js View on Github external
const validateArgs = (desc, args) => {
  if (!desc) return {}
  const argsSchema = map(desc.meta, 'args')[0]
  if (!argsSchema) return {}
  const { value, error } = Joi.validate(args, argsSchema)
  if (error) throw error
  return value
}
github muoncore / muon-node / muon / domain / events.js View on Github external
eventType: "RequestMade",
                  protocol: "request",
                  targetService: serviceRequest.hostname,
                  sourceService: sourceService,
                  url: remoteServiceUrl,
                  channelOperation: "NORMAL",
                   "Content-Type": "application/json",
                   sourceAvailableContentTypes: ["application/json"]
              },
              payload: {
                  data: payload
              }
          };


   var validatedEvent = Joi.validate(event, schema);
   logger.trace('event: %s', JSON.stringify(event));
   if (validatedEvent.error) {
        logger.warn('invalid event: \n', event);
        logger.debug('joi validatedEvent: ' + JSON.stringify(validatedEvent.error.details));
       throw new Error('Error! problem validating rpc event schema: ' + JSON.stringify(validatedEvent.error));
   }
   return validatedEvent.value;

};