How to use joi - 10 common examples

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 glennjones / hapi-swagger / test / properties.js View on Github external
lab.test('parse type number', (done) => {

        // mapped direct to openapi
        expect(properties.parseProperty('x', Joi.number().integer())).to.equal({ 'type': 'integer' });
        expect(properties.parseProperty('x', Joi.number().min(5))).to.equal({ 'type': 'number', 'minimum': 5 });
        expect(properties.parseProperty('x', Joi.number().max(10))).to.equal({ 'type': 'number', 'maximum': 10 });

        // x-* mappings
        expect(properties.parseProperty('x', Joi.number().greater(10))).to.equal({ 'type': 'number', 'x-constraint': { 'greater': 10 } });
        expect(properties.parseProperty('x', Joi.number().less(10))).to.equal({ 'type': 'number', 'x-constraint': { 'less': 10 } });
        expect(properties.parseProperty('x', Joi.number().precision(2))).to.equal({ 'type': 'number', 'x-constraint': { 'precision': 2 } });
        expect(properties.parseProperty('x', Joi.number().multiple(2))).to.equal({ 'type': 'number', 'x-constraint': { 'multiple': 2 } });
        expect(properties.parseProperty('x', Joi.number().positive())).to.equal({ 'type': 'number', 'x-constraint': { 'positive': true } });
        expect(properties.parseProperty('x', Joi.number().negative())).to.equal({ 'type': 'number', 'x-constraint': { 'negative': true } });

        done();
    });
github glennjones / hapi-swagger / test / properties.js View on Github external
lab.test('parse type date', (done) => {

        expect(properties.parseProperty('x', Joi.date())).to.equal({ 'type': 'string', 'format': 'date' });

        /*  not yet 'x',
        date.min(date)
        date.max(date)
        date.format(format)
        date.iso()
        */
        done();
    });
github kidtronnix / hapi-dash / servers / gui / auth / index.js View on Github external
handler: function(request, next) {


                var newUser = request.payload;

                var validSchema = Joi.object().keys({
                    fname: Joi.string().required(),
                    lname: Joi.string().required(),
                    email: Joi.string().email().required(),
                    password: Joi.string().alphanum().required().min(5).max(15),
                    password2: Joi.any().valid(newUser.password)
                })

                // We got everything we need to create a new user
                Joi.validate(newUser, validSchema, {abortEarly: false}, function (err, value) {

                    if(err !== null) {
                        console.log(err)

                        var message = '';
                        for(i=0; i < err.details.length; i++)
                        {
                            var _message = err.details[i].message;
                            if(err.details[i].path == 'password2') {
                                message += 'Passwords must match. '
                            } else {
                                message += _message.substr(0, 1).toUpperCase() + _message.substr(1) +'. ';
github muraljs / joiql / examples / artsy / index.js View on Github external
const joiql = require('../../')
const app = require('express')()
const graphqlHTTP = require('express-graphql')
const Article = require('./models/article')
const Artwork = require('./models/artwork')
const Artist = require('./models/artist')
const Show = require('./models/show')
const { object, string } = require('joi')
const artsyXapp = require('artsy-xapp')
const cache = require('./middleware/cache')
const rest = require('./middleware/rest')

const api = joiql({
  query: {
    artwork: object(Artwork.Attrs).meta({ args: { id: string().required() } }),
    article: object(Article.Attrs).meta({ args: { id: string().required() } }),
    artist: object(Artist.Attrs).meta({ args: { id: string().required() } }),
    show: object(Show.Attrs).meta({ args: { id: string().required() } })
  }
})

// JoiQL Middleware
api.on('query', cache.get)
api.on('query', rest.fetch)
api.on('query.artwork.fields.artist', Artwork.resolveArtist)
api.on('query', cache.set)

// Start express server
app.use('/graphql', graphqlHTTP({
  schema: api.schema,
  graphiql: true
}))
github magda-io / magda / magda-search-api-node / src / createApiRouter.ts View on Github external
// const status = {
    //     probes: {
    //         database: database.check.bind(database),
    //         auth: createServiceProbe(options.authApiUrl)
    //     }
    // };
    // installStatusRouter(router, status);

    const baseValidators = {
        start: joi.number().default(0),
        limit: joi.number().default(10),
        publisher: joi
            .array()
            .items(joi.string())
            .optional(),
        dateFrom: joi.string().optional(),
        dateTo: joi.string().optional(),
        region: joi
            .alternatives([joi.array().items(joi.string()), joi.string()])
            .optional(),
        format: joi
            .array()
            .items(joi.string())
            .optional(),
        publishingState: joi
            .array()
            .items(joi.string())
            .optional()
    };

    const facetQueryValidation = {
        query: {
github godaddy / timings / routes / v2 / post-routes.js View on Github external
function validateSchema(route, req, pu) {
  // Schema for request validation (extended in individual routes)

  // Add base schema
  const baseSchema = joi.object({
    sla: joi.object({
      pageLoadTime: joi.number().integer(),
      visualCompleteTime: joi.number().integer()
    }).length(1).required(),
    baseline: joi.object({
      days: joi.number().integer(),
      perc: joi.number().integer().max(100),
      padding: joi.number().min(1),
      src: joi.string().allow(''),
      aggField: joi.string().allow(''),
      searchUrl: joi.string().allow(''),
      incl: joi.object(),
      excl: joi.object()
    }),
    flags: joi.object({
      assertBaseline: joi.boolean(),
      assertRum: joi.boolean(),
      debug: joi.boolean(),
      esTrace: joi.boolean(),
      esCreate: joi.boolean(),
      passOnFailedAssert: joi.boolean()
github screwdriver-cd / screwdriver / plugins / jobs / metrics.js View on Github external
'use strict';

const boom = require('boom');
const joi = require('joi');
const { setDefaultTimeRange, validTimeRange } = require('../helper.js');
const MAX_DAYS = 180; // 6 months
const schema = require('screwdriver-data-schema');
const jobMetricListSchema = joi.array().items(joi.object());
const jobIdSchema = joi.reach(schema.models.job.base, 'id');

module.exports = () => ({
    method: 'GET',
    path: '/jobs/{id}/metrics',
    config: {
        description: 'Get build metrics for this job',
        notes: 'Returns list of build metrics for the given job',
        tags: ['api', 'jobs', 'metrics'],
        auth: {
            strategies: ['token'],
            scope: ['user', '!guest', 'pipeline']
        },
        plugins: {
            'hapi-swagger': {
                security: [{ token: [] }]
github clarkie / dynogels / examples / globalSecondaryIndexes.js View on Github external
const async = require('async');

// http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html

const AWS = dynogels.AWS;
AWS.config.update({ region: 'us-east-1' });

const GameScore = dynogels.define('example-global-index', {
  hashKey: 'userId',
  rangeKey: 'gameTitle',
  schema: {
    userId: Joi.string(),
    gameTitle: Joi.string(),
    topScore: Joi.number(),
    topScoreDateTime: Joi.date(),
    wins: Joi.number(),
    losses: Joi.number()
  },
  indexes: [{
    hashKey: 'gameTitle',
    rangeKey: 'topScore',
    name: 'GameTitleIndex',
    type: 'global',
    projection: { NonKeyAttributes: ['wins'], ProjectionType: 'INCLUDE' }
  },
  { hashKey: 'gameTitle', rangeKey: 'losses', name: 'GameLosersIndex', type: 'global' }
  ]
});

const data = [
  { userId: '101', gameTitle: 'Galaxy Invaders', topScore: 5842, wins: 10, losses: 5, topScoreDateTime: new Date(2012, 1, 3, 8, 30) },
  { userId: '101', gameTitle: 'Meteor Blasters', topScore: 1000, wins: 12, losses: 3, topScoreDateTime: new Date(2013, 1, 3, 8, 30) },
github shahar603 / Launch-Dashboard-API / src / models / launch.js View on Github external
// Raw telemetry entry
const RawTelemetrySchema = {
    time: Joi.number(),
    velocity: Joi.number(),
    altitude: Joi.number()
};

// Analysed telemetry entry
const AnalysedTelemetrySchema = {
    time: Joi.number(),
    velocity: Joi.number(),
    altitude: Joi.number(),
    velocity_y: Joi.number(),
    velocity_x: Joi.number(),
    acceleration: Joi.number(),
    downrange_distance: Joi.number(),
    angle: Joi.number(),
    q: Joi.number()
};

// Raw telemetry of a specific stage
const StageRawTelemetrySchema = {
    stage: Joi.number(),
    telemetry: Joi.array().items(RawTelemetrySchema)
};

// Analysed telemetry of a specific stage
const StageAnalysedTelemetrySchema = {
    stage: Joi.number().integer().min(0),
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