How to use the @hapi/joi.validate function in @hapi/joi

To help you get started, we’ve selected a few @hapi/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 openmobilityfoundation / mds-core / packages / mds-policy-author / api.ts View on Github external
app.post(pathsFor('/policies'), checkAccess(scopes => scopes.includes('policies:write')), async (req, res) => {
    const policy = { policy_id: uuid(), ...req.body }
    const validation = Joi.validate(policy, policySchema)
    const details = validation.error ? validation.error.details : null

    if (details) {
      await log.error('invalid policy json', details)
      return res.status(400).send(details)
    }

    try {
      await db.writePolicy(policy)
      return res.status(201).send(policy)
    } catch (err) {
      if (err.code === '23505') {
        return res.status(409).send({ result: `policy ${policy.policy_id} already exists! Did you mean to PUT?` })
      }
      /* istanbul ignore next */
      await log.error('failed to write policy', err)
github anttiviljami / serverless-openapi-joi / src / handler.ts View on Github external
if (validation) {
      const input = _.omitBy(
        {
          headers,
          pathParameters,
          queryStringParameters,
          ...payload,
        },
        _.isNil,
      );

      const validationDefaults = {
        queryStringParameters: Joi.object().unknown(),
      };

      const validationResult = Joi.validate(input, {
        ...validationDefaults,
        ...validation,
        headers: Joi.object(headers || {}).unknown(), // headers are always partially defined
      });

      // throw a 400 error if there are any validation errors
      if (validationResult.error) {
        throw Boom.badRequest(validationResult.error.message);
      }
    }

    // pass event to handler enriched with parsed payload
    const res = await handler({ ...event, ...payload }, context);
    return {
      statusCode: 200,
      ...res,
github metoikos / hapi-moon / test / validators.js View on Github external
it('should reject invalid email', async () => {
        let data = {
            name: 'John Doe',
            email: 'sample@testcom',
            password: 'asd12345',
            passwordMatch: 'asd12345',
        };
        const result = Joi.validate(data, validators.register, {abortEarly: false});

        expect(result.error).not.to.null();
        expect(result.error).to.exist();
    });
github tlivings / enjoi / test / test-options.js View on Github external
'definitions': {
                'firstname': {
                    'type': 'string'
                }
            }
        }, {
            subSchemas: {
                'definitions': {
                    'surname': {
                        'type': 'string'
                    }
                }
            }
        });

        Joi.validate({ firstname: 'Joe', surname: 'Doe' }, schema, function (error, value) {
            t.ok(!error, 'no error.');
        });
    });
github tlivings / enjoi / test / test-types.js View on Github external
t.plan(3);

        const schema = Enjoi.schema({
            'type': 'string',
            'format': 'ipv6'
        });

        Joi.validate('', schema, function (error, value) {
            t.ok(error, "empty string.");
        });
        
        Joi.validate('asdf', schema, function (error, value) {
            t.ok(error, "bad ipv6 error.");
        });

        Joi.validate('::1', schema, function (error, value) {
            t.ok(!error, "good ipv6.");
        });

    });
github tlivings / enjoi / test / test-directives.js View on Github external
]
        });

        Joi.validate({ a: 'string' }, schema, function (error, value) {
            t.ok(!error, 'no error.');
        });

        Joi.validate({}, schema, function (error, value) {
            t.ok(!error, 'no error.');
        });

        Joi.validate(undefined, schema, function (error, value) {
            t.ok(!error, 'no error.');
        });

        Joi.validate({ b: 10 }, schema, function (error, value) {
            t.ok(!error, 'no error.');
        });

        Joi.validate({ a: 'string', b: 10 }, schema, function (error, value) {
            t.ok(error, 'error.');
        });

        Joi.validate({ a: 'string', b: null }, schema, function (error, value) {
            t.ok(error, 'error.');
        });

        Joi.validate({ a: null, b: 10 }, schema, function (error, value) {
            t.ok(error, 'error.');
        });

        Joi.validate({ a: null, b: null }, schema, function (error, value) {
github nearform / udaru / packages / udaru-core / lib / ops / policyOps.js View on Github external
readSharedPolicy: function readSharedPolicy ({ id }, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      Joi.validate({ id }, validationRules.readSharedPolicy, function (err) {
        if (err) return cb(Boom.badRequest(err))

        const sqlQuery = SQL`
          SELECT  *
          FROM policies
          WHERE id = ${id}
          AND org_id IS NULL
        `
        db.query(sqlQuery, function (err, result) {
          if (err) return cb(Boom.badImplementation(err))
          if (result.rowCount === 0) return cb(Boom.notFound())

          return cb(null, mapping.policy(result.rows[0]))
        })
      })
github gridsome / gridsome / gridsome / lib / app / loadConfig.js View on Github external
function normalizePermalinks (permalinks = {}) {
  const { error, value } = Joi.validate(permalinks, permalinksSchema)

  if (error) {
    throw new Error(error.message)
  }

  if (value.slugify && typeof value.slugify.use === 'string') {
    value.slugify.use = require(value.slugify.use)
  } else if (typeof value.slugify === 'function') {
    value.slugify = { use: value.slugify, options: {}}
  }

  return Object.freeze(value)
}
github nearform / udaru / packages / udaru-core / lib / ops / userOps.js View on Github external
(job, next) => {
          Joi.validate({ id, organizationId }, validationRules.deleteUserFromTeams, (err) => {
            if (err) return next(Boom.badRequest(err))
            next()
          })
        },
        (job, next) => {
github cube-js / cube.js / packages / cubejs-schema-compiler / compiler / CubeValidator.js View on Github external
validate(cube, errorReporter) {
    Joi.validate(cube, cubeSchema, (err) => {
      if (err) {
        errorReporter.error(err.message);
      } else {
        this.validCubes[cube.name] = true;
      }
    });
  }