How to use @hapi/joi - 10 common examples

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 badges / shields / services / twitch / twitch.tester.js View on Github external
!runnerConfig.private.twitch_client_secret
  if (noToken) {
    console.warn(
      'No Twitch client credentials configured. Service tests will be skipped. Add credentials in local.yml to run these tests.'
    )
  }
  return noToken
}

// the first request would take longer since we need to wait for a token
t.create('Status of andyonthewings')
  .skipWhen(checkShouldSkip)
  .get('/status/andyonthewings.json')
  .expectBadge({
    label: 'twitch',
    message: Joi.equal('live', 'offline').required(),
    link: ['https://www.twitch.tv/andyonthewings'],
  })

// the second request should take shorter time since we can reuse the previous token
t.create('Status of noopkat')
  .skipWhen(checkShouldSkip)
  .get('/status/noopkat.json')
  .expectBadge({
    label: 'twitch',
    message: Joi.equal('live', 'offline').required(),
    link: ['https://www.twitch.tv/noopkat'],
  })
github badges / shields / services / travis / travis-build.tester.js View on Github external
'use strict'

const Joi = require('@hapi/joi')
const { isBuildStatus } = require('../build-status')
const t = (module.exports = require('../tester').createServiceTester())

// Travis (.org) CI

t.create('build status on default branch')
  .get('/rust-lang/rust.json')
  .expectBadge({
    label: 'build',
    message: Joi.alternatives().try(isBuildStatus, Joi.equal('unknown')),
  })

t.create('build status on named branch')
  .get('/rust-lang/rust/stable.json')
  .expectBadge({
    label: 'build',
    message: Joi.alternatives().try(isBuildStatus, Joi.equal('unknown')),
  })

t.create('unknown repo')
  .get('/this-repo/does-not-exist.json')
  .expectBadge({ label: 'build', message: 'unknown' })

t.create('invalid svg response')
  .get('/foo/bar.json')
  .intercept(nock =>
github IcedFrisby / IcedFrisby / test / frisby_httpbin.js View on Github external
},
      })
      .expectStatus(200)
      .expectHeaderContains('content-type', 'application/json')
      .expectJSONTypes({
        // use the JSONTypes to check for data and headers. We don't really care about anything else.
        data: Joi.string().valid(
          'data:application/octet-stream;base64,' +
            Buffer.from(data).toString('base64')
        ),
        headers: Joi.object()
          .required()
          .keys({
            Accept: Joi.any(),
            'Accept-Encoding': Joi.any(),
            'Cache-Control': Joi.any(),
            Connection: Joi.any(),
            'Content-Type': Joi.string()
              .required()
              .valid('application/octet-stream'),
            'Content-Length': Joi.string()
              .required()
              .valid('1024'),
            Host: Joi.any(),
          }),
        args: Joi.any(),
        files: Joi.any(),
        form: Joi.any(),
        json: Joi.any(),
        origin: Joi.any(),
        url: Joi.string()
          .required()
github hydra-newmedia / hapi-sentry / index.js View on Github external
exports.register = (server, options) => {
  const opts = joi.attempt(options, schema, 'Invalid hapi-sentry options:');

  let Sentry = opts.client;
  // initialize own sentry client if none passed as option
  if (opts.client.dsn !== undefined) {
    Sentry = require('@sentry/node');
    Sentry.init(opts.client);
  }

  // initialize global scope if set via plugin options
  if (opts.scope) {
    Sentry.configureScope(scope => {
      if (opts.scope.tags) opts.scope.tags.forEach(tag => scope.setTag(tag.name, tag.value));
      if (opts.scope.level) scope.setLevel(opts.scope.level);
      if (opts.scope.extra) {
        Object.keys(opts.scope.extra).forEach(key => scope.setExtra(key, opts.scope.extra[key]));
      }
github webextension-toolbox / webpack-webextension-plugin / manifest-utils / validate.js View on Github external
content_security_policy: Joi.string(),

  // This key must be present if the extension contains the _locales directory, and must be absent otherwise. It identifies a subdirectory of _locales, and this subdirectory will be used to find the default strings for your extension.
  default_locale: Joi.string(),

  // A short description of the extension, intended for display in the browser's user interface.
  description: Joi.string(),

  // The name of the extension's developer and their homepage URL, intended for display in the browser's user interface.
  developer: Joi.object({
    name: Joi.string(),
    url: Joi.string()
  }),

  // Use this key to enable your extension to extend the browser's built-in devtools.
  devtools_page: Joi.string(),

  // URL for the extension's home page.
  homepage_url: Joi.string(),

  // The icons key specifies icons for your extension. Those icons will be used to represent the extension in components such as the Add-ons Manager.
  icons: Joi.object(),

  // Use the incognito key to control how the extension works with private browsing windows.
  incognito: Joi.string().valid('spanning', 'split', 'not_allowed'),

  // This key specifies the version of manifest.json used by this extension.
  // Currently, this must always be 2.
  manifest_version: Joi.number().default(2),

  // Name of the extension. This is used to identify the extension in the browser's user interface and on sites like addons.mozilla.org.
  name: Joi.string().max(45).required(),
github WalletConnect / firebase-walletconnect-push / functions / src / routes / register.ts View on Github external
export const register = async (req: Request): Promise => {
    try {
        // validate POST data
        await Joi.object({
            bridge: Joi.string().uri().required(),
            topic: Joi.string().uuid().required(),
            type: Joi.string().valid('fcm').required(),
            token: Joi.string().token().required(),
            peerName: Joi.string(),
            language: Joi.string()
        }).validateAsync(req.body);

        // save data in firestore
        await setRegistration(req.body);

        // register webhook on the bridge
        const webhook = `${req.protocol}://${req.headers.host}${req.baseUrl}`;
        const bridgeSubscribeResponse = await axios.post(
            `${req.body.bridge.replace(/\/$/, '')}/subscribe`, 
            {
                topic: req.body.topic,
                webhook
github hapijs / vision / lib / schemas.js View on Github external
options: Joi.object()
    })
]);


// Manager schemas

exports.viewOverride = Joi.object({
    path: [Joi.array().items(Joi.string()), Joi.string()],
    relativeTo: Joi.string(),
    compileOptions: Joi.object(),
    runtimeOptions: Joi.object(),
    layout: Joi.string().allow(false, true),
    layoutKeyword: Joi.string(),
    layoutPath: [Joi.array().items(Joi.string()), Joi.string()],
    encoding: Joi.string(),
    allowAbsolutePaths: Joi.boolean(),
    allowInsecureAccess: Joi.boolean(),
    contentType: Joi.string()
});


exports.viewBase = exports.viewOverride.keys({
    partialsPath: [Joi.array().items(Joi.string()), Joi.string()],
    helpersPath: [Joi.array().items(Joi.string()), Joi.string()],
    isCached: Joi.boolean(),
    compileMode: Joi.string().valid('sync', 'async'),
    defaultExtension: Joi.string()
});


exports.manager = exports.viewBase.keys({
github badges / shields / services / nuget / nuget-v3-service-family.js View on Github external
// both in years, the yearly number of queries for the endpoint are 1/x,
    // and when the endpoint changes, we wait for up to x years to get the
    // right endpoint.
    // So the waiting time within n years is n*l/x + x years, for which a
    // derivation yields an optimum at x = sqrt(n*l), roughly 42 minutes.
    intervalMillis: 42 * 60 * 1000,
    json: true,
    scraper: json =>
      json.resources.filter(
        resource => resource['@type'] === 'SearchQueryService'
      ),
  })
  return randomElementFrom(searchQueryServices)['@id']
}

const schema = Joi.object({
  data: Joi.array()
    .items(
      Joi.object({
        versions: Joi.array()
          .items(
            Joi.object({
              version: Joi.string().required(),
            })
          )
          .default([]),
        totalDownloads: Joi.number().integer(),
        totaldownloads: Joi.number().integer(),
      })
    )
    .max(1)
    .default([]),
github badges / shields / services / nodeping / nodeping-uptime.service.js View on Github external
'use strict'

const Joi = require('@hapi/joi')
const { colorScale } = require('../color-formatters')
const { BaseJsonService } = require('..')

const colorFormatter = colorScale([99, 99.5, 100])

const rowSchema = Joi.object().keys({
  uptime: Joi.number()
    .precision(3)
    .min(0)
    .max(100),
})

const schema = Joi.array()
  .items(rowSchema)
  .min(1)

/*
 * this is the checkUuid for the NodePing.com (as used on the [example page](https://nodeping.com/reporting.html#results))
 */
const sampleCheckUuid = 'jkiwn052-ntpp-4lbb-8d45-ihew6d9ucoei'

// TODO: support for custom # of days
// TODO: support for custom color thresholds
github alexandercerutti / passkit-generator / src / schema.ts View on Github external
numberStyle?: string;
}

const field = Joi.object().keys({
	attributedValue: Joi.alternatives(Joi.string().allow(""), Joi.number(), Joi.date().iso()),
	changeMessage: Joi.string(),
	dataDetectorType: Joi.array().items(Joi.string().regex(/(PKDataDetectorTypePhoneNumber|PKDataDetectorTypeLink|PKDataDetectorTypeAddress|PKDataDetectorTypeCalendarEvent)/, "dataDetectorType")),
	label: Joi.string().allow(""),
	textAlignment: Joi.string().regex(/(PKTextAlignmentLeft|PKTextAlignmentCenter|PKTextAlignmentRight|PKTextAlignmentNatural)/, "graphic-alignment"),
	key: Joi.string().required(),
	value: Joi.alternatives(Joi.string().allow(""), Joi.number(), Joi.date().iso()).required(),
	semantics,
	// date fields formatters, all optionals
	dateStyle: Joi.string().regex(/(PKDateStyleNone|PKDateStyleShort|PKDateStyleMedium|PKDateStyleLong|PKDateStyleFull)/, "date style"),
	ignoreTimeZone: Joi.boolean(),
	isRelative: Joi.boolean(),
	timeStyle: Joi.string().regex(/(PKDateStyleNone|PKDateStyleShort|PKDateStyleMedium|PKDateStyleLong|PKDateStyleFull)/, "date style"),
	// number fields formatters, all optionals
	currencyCode: Joi.string()
		.when("value", {
			is: Joi.number(),
			otherwise: Joi.string().forbidden()
		}),
	numberStyle: Joi.string()
		.regex(/(PKNumberStyleDecimal|PKNumberStylePercent|PKNumberStyleScientific|PKNumberStyleSpellOut)/)
		.when("value", {
			is: Joi.number(),
			otherwise: Joi.string().forbidden()
		}),
});

export interface Beacon {