How to use the joi.attempt 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 rethinkdb / horizon / server / src / client.js View on Github external
parse_request(data, schema) {
    let request;
    try {
      request = JSON.parse(data);
    } catch (err) {
      return this.close({ request_id: null,
                          error: `Invalid JSON: ${err}`,
                          error_code: 0 });
    }

    try {
      return Joi.attempt(request, schema);
    } catch (err) {
      const detail = err.details[0];
      const err_str = `Request validation error at "${detail.path}": ${detail.message}`;
      const request_id = request.request_id === undefined ? null : request.request_id;

      if (request.request_id === undefined) {
        // This is pretty much an unrecoverable protocol error, so close the connection
        this.close({ request_id, error: `Protocol error: ${err}`, error_code: 0 });
      } else {
        this.send_error({ request_id }, err_str);
      }
    }
  }
github scality / backbeat / lib / BackbeatProducer.js View on Github external
constructor(config) {
        super();

        const configJoi = {
            zookeeper: {
                connectionString: joi.string().required(),
            },
            sslOptions: joi.object(),
            topic: joi.string().required(),
            partition: joi.number(),
        };
        const validConfig = joi.attempt(config, configJoi,
                                        'invalid config params');
        const { zookeeper, sslOptions, topic, partition } = validConfig;

        this._partition = partition;
        this._zookeeperEndpoint = zookeeper.connectionString;
        this._log = new Logger(CLIENT_ID);
        this._topic = topic;
        this._ready = false;
        // create zookeeper client
        this._client = new Client(this._zookeeperEndpoint, CLIENT_ID,
            { sslOptions });
        // create a new producer instance
        this._producer = new Producer(this._client, {
            // configuration for when to consider a message as acknowledged
            requireAcks: REQUIRE_ACKS,
            // amount of time in ms. to wait for all acks
github yonjah / ralphi / hapi-plugin / lib / plugin.js View on Github external
function register (server, options, next) { // eslint-disable-line no-unused-vars

	options = joi.attempt(options, optionsSchema, 'options');
	const client = options.client;


	server.ext(options.ext, async (request, h) => {
		let limit;
		const settings = getSettings(request.route.settings.plugins.ralphi);

		if (!settings) {
			return h.continue;
		}

		try {
			limit = await client.take(settings.bucket, settings.getKey(request));
		} catch (e) {
			request.log(['error'], e);
			if (settings.onError) {
github vudash / vudash / packages / widget-statistic / src / server / widget.spec.js View on Github external
it('With provided colour', () => {
      const conf = { colour: '#f00' }
      const config = Joi.attempt(conf, validation)
      expect(config.colour).to.equal('#f00')
    })
github ediket / nothinkdb / src / Table.js View on Github external
static attempt(data = null) {
    return Joi.attempt(data, this.schema());
  }
github christophercliff / flatmarket / packages / flatmarket-theme-bananas / karma.config.js View on Github external
var commander = require('commander')
var Joi = require('joi')
var testWebpackConfig = require('./webpack.config.test')

var MODES = {
    coverage: {
        id: 'coverage',
    },
    dev: {
        id: 'dev',
    },
    test: {
        id: 'test',
    },
}
var options = Joi.attempt(_.pick(commander
    .option('--mode [mode]')
    .parse(process.argv), [
        'mode',
    ]), Joi.object().keys({
        mode: Joi.string().valid(_.pluck(MODES, 'id')).default(MODES.test.id),
    }))

module.exports = function (config) {
    var override
    switch (options.mode) {
        case MODES.coverage.id:
            override = {
                coverageReporter: {
                    reporters: [
                        {
                            type: 'text',
github nearform / leaistic / lib / es / logger.js View on Github external
const pino = require('pino')
const JSONtruncate = require('json-truncate')
const Joi = require('joi')

const DEBUG_ES = Joi.attempt(process.env.LEAISTIC_DEBUG_ES_IO,
  Joi.boolean().default(true).empty('').label('Environment Variable LEAISTIC_DEBUG_ES_IO'))
const MAX_BODY_LENGTH = Joi.attempt(process.env.LEAISTIC_MAX_ES_BODY_LENGTH,
  Joi.number().default(240).empty('').label('Environment Variable LEAISTIC_MAX_ES_BODY_LENGTH'))
const MAX_JSON_DEPTH = Joi.attempt(process.env.LEAISTIC_MAX_JSON_DEPTH,
  Joi.number().default(4).empty('').label('Environment Variable LEAISTIC_MAX_ES_JSON_DEPTH'))

const ES_LOG_LEVEL_OK = Joi.attempt(process.env.LEAISTIC_ES_LOG_LEVEL_OK,
  Joi.string().trim().lowercase().default('info').empty('').valid('trace', 'debug', 'info', 'warn', 'error', 'fatal').label('Environment Variable LEAISTIC_ES_LOG_LEVEL_OK'))
const ES_LOG_LEVEL_ERROR = Joi.attempt(process.env.LEAISTIC_ES_LOG_LEVEL_ERROR,
  Joi.string().trim().lowercase().default('error').empty('').valid('trace', 'debug', 'info', 'warn', 'error', 'fatal').label('Environment Variable LEAISTIC_ES_LOG_LEVEL_ERROR'))
const ES_LOG_THRESHOLD = Joi.attempt(process.env.LEAISTIC_ES_LOG_THRESHOLD,
  Joi.string().trim().lowercase().default('info').empty('').valid('trace', 'debug', 'info', 'warn', 'error', 'fatal').label('Environment Variable LEAISTIC_ES_LOG_THRESHOLD'))

const defaultParseConfig = {maxDepth: MAX_JSON_DEPTH, maxLength: MAX_BODY_LENGTH}

const parse = (strOrJson = '', config = defaultParseConfig) => {
github davidgljay / nametag / horizon / server / src / auth / github.js View on Github external
function github (horizon, raw_options) {
  const options = Joi.attempt(raw_options, options_schema)
  const client_id = options.id
  const client_secret = options.secret
  const provider = options.path

  const oauth_options = { horizon, provider }

  oauth_options.make_acquire_url = (state, redirect_uri) =>
    url.format({ protocol: 'https',
      host: 'github.com',
      pathname: '/login/oauth/authorize',
      query: { client_id, redirect_uri, state } })

  oauth_options.make_token_request = (code, redirect_uri) => {
    const req = https.request({ method: 'POST',
      host: 'github.com',
      path: '/login/oauth/access_token',
github rethinkdb / horizon / server / src / auth / utils.js View on Github external
const oauth2 = (raw_options) => {
  const options = Joi.attempt(raw_options, options_schema);

  const horizon = options.horizon;
  const provider = options.provider;
  const make_acquire_url = options.make_acquire_url;
  const make_token_request = options.make_token_request;
  const make_inspect_request = options.make_inspect_request;
  const extract_id = options.extract_id;

  const self_url = (host, path) =>
    url.format({ protocol: 'https', host: host, pathname: path });

  const make_success_url = (horizon_token) =>
    url.format(extend_url_query(horizon._auth._success_redirect, { horizon_token }));

  const make_failure_url = (horizon_error) =>
    url.format(extend_url_query(horizon._auth._failure_redirect, { horizon_error }));
github outmoded / penseur / lib / db.js View on Github external
names.forEach((name) => {

            tables[name] = Joi.attempt(normalize(tables[name]), internals.schema.table, `Invalid table options: ${name}`);
        });