How to use the joi.required 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 simonrenoult / nodejs-application-architecture / index.js View on Github external
conf.db.password,
    conf.db.sequelize
  );
}

// Schemas and models
const Product = sequelize.define("product", {
  name: Sequelize.STRING,
  price: Sequelize.INTEGER,
  weight: Sequelize.INTEGER
});

const productSchema = Joi.object().keys({
  name: Joi.required(),
  price: Joi.required(),
  weight: Joi.required()
});

const Order = sequelize.define("order", {
  status: {
    type: Sequelize.ENUM("pending", "cancelled", "paid"),
    defaultValue: "pending"
  },
  shipment_amount: {
    type: Sequelize.INTEGER,
    defaultValue: 25
  },
  total_amount: Sequelize.INTEGER,
  total_weight: Sequelize.INTEGER
});

Order.hasMany(Product, { as: "ProductList" });
github microsoft / pai / src / rest-server / src / config / v2 / user.js View on Github external
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

// module dependencies
const Joi = require('joi');

// define the input schema for the 'update user extension' api
const userExtensionUpdateInputSchema = Joi.object().keys({
  extension: Joi.object().pattern(/\w+/, Joi.required()),
}).required();

// define the input schema for the 'update user virtualCluster' api
const userVirtualClusterUpdateInputSchema = Joi.object().keys({
  virtualCluster: Joi.array().items(Joi.string()).required(),
});

// define the input schema for the 'update user grouplist' api
const userGrouplistUpdateInputSchema = Joi.object().keys({
  grouplist: Joi.array().items(Joi.string()).required(),
});

// define the input schema for the 'update user password' api
const userPasswordUpdateInputSchema = Joi.object().keys({
  oldPassword: Joi.string().min(6).default('defaultpai'),
  newPassword: Joi.string().min(6).required(),
github elastic / kibana / src / plugins / home / server / services / tutorials / lib / tutorial_schema.ts View on Github external
NUMBER: 'number',
  STRING: 'string',
};

const TUTORIAL_CATEGORY = {
  LOGGING: 'logging',
  SIEM: 'siem',
  METRICS: 'metrics',
  OTHER: 'other',
};

const dashboardSchema = Joi.object({
  id: Joi.string().required(), // Dashboard saved object id
  linkLabel: Joi.string().when('isOverview', {
    is: true,
    then: Joi.required(),
  }),
  // Is this an Overview / Entry Point dashboard?
  isOverview: Joi.boolean().required(),
});

const artifactsSchema = Joi.object({
  // Fields present in Elasticsearch documents created by this product.
  exportedFields: Joi.object({
    documentationUrl: Joi.string().required(),
  }),
  // Kibana dashboards created by this product.
  dashboards: Joi.array()
    .items(dashboardSchema)
    .required(),
  application: Joi.object({
    path: Joi.string().required(),
github flaviuse / mern-authentication / client / node_modules / workbox-build / src / entry-points / options / common-generate-schema.js View on Github external
headers: joi.object(),
      }).or('statuses', 'headers'),
      cacheName: joi.string(),
      expiration: joi.object().keys({
        maxEntries: joi.number().min(1),
        maxAgeSeconds: joi.number().min(1),
        purgeOnQuotaError: joi.boolean().default(defaults.purgeOnQuotaError),
      }).or('maxEntries', 'maxAgeSeconds'),
      networkTimeoutSeconds: joi.number().min(1),
      plugins: joi.array().items(joi.object()),
      fetchOptions: joi.object(),
      matchOptions: joi.object(),
    }).with('expiration', 'cacheName'),
  }).requiredKeys('urlPattern', 'handler')).when('navigationPreload', {
    is: true,
    then: joi.required(),
  }),
  skipWaiting: joi.boolean().default(defaults.skipWaiting),
}).rename('ignoreUrlParametersMatching', 'ignoreURLParametersMatching', {
  ignoreUndefined: true,
  override: true,
});
github MoonMail / MoonMail / lists-microservice / src / domain / RecipientModel.js View on Github external
static get updateSchema() {
    return Joi.object({
      status: Joi.string().valid(Object.values(RecipientModel.statuses)),
      isConfirmed: Joi.boolean(),
      metadata: Joi.object().pattern(/^[A-Za-z_]+[A-Za-z0-9_]*$/, Joi.required()),
      updatedAt: Joi.number().default(moment().unix())
    });
  }
github medfreeman / remark-generic-extensions / src / utils / optionsSchema.js View on Github external
.items(
    joi.object({
      type: hastNodeTypeRegex,
      tagName: html5TagNameRegex.when("type", {
        is: "element",
        then: joi.required()
      }),
      value: joi
        .string()
        .when("type", {
          is: "comment",
          then: joi.required()
        })
        .when("type", {
          is: "text",
          then: joi.required()
        }),
      properties: joi
        .object({
          class: joi.any().forbidden(),
          for: joi.any().forbidden()
        })
        .pattern(hastPropertyNameRegex, joi.any()),
      children: joi.lazy(() => hastSchema)
    })
  )
  .description("hast schema");

const schema = joi.object({
  debug: joi.boolean(),
  placeholderAffix: joi.string(),
  elements: joi.object(undefined).pattern(
github blockstack / blockstack-browser / native / windows / BlockstackBrowser / Resources / corsproxy-https / node_modules / hapi / lib / schema.js View on Github external
});


internals.plugin = internals.register.keys({
    register: Joi.func().keys({
        attributes: Joi.object({
            pkg: Joi.object({
                name: Joi.string(),
                version: Joi.string().default('0.0.0')
            })
                .unknown()
                .default({
                    version: '0.0.0'
                }),
            name: Joi.string()
                .when('pkg.name', { is: Joi.exist(), otherwise: Joi.required() }),
            version: Joi.string(),
            multiple: Joi.boolean().default(false),
            dependencies: Joi.array().items(Joi.string()).single(),
            connections: Joi.boolean().default(true),
            once: Joi.boolean().valid(true)
        })
            .required()
            .unknown()
    })
        .required(),
    options: Joi.any()
})
    .without('once', 'options')
    .unknown();
github nodemailer / mailcast / routes / account / settings / index.js View on Github external
resetDkim: Joi.boolean()
                .truthy(['Y', 'true', 'yes', 'on', 1])
                .falsy(['N', 'false', 'no', 'off', 0, ''])
                .default(false),
            global_site_recaptchaEnabled: Joi.boolean()
                .truthy(['Y', 'true', 'yes', 'on', 1])
                .falsy(['N', 'false', 'no', 'off', 0, ''])
                .default(false),
            global_site_recaptchaSiteKey: Joi.string()
                .empty('')
                .trim()
                .max(256)
                .label('Recaptcha Site Key')
                .when('global_site_recaptchaEnabled', {
                    is: Joi.equal(true),
                    then: Joi.required()
                }),
            global_site_recaptchaSecretKey: Joi.string()
                .empty('')
                .trim()
                .max(256)
                .label('Recaptcha Secret Key')
                .when('global_site_recaptchaEnabled', {
                    is: Joi.equal(true),
                    then: Joi.required()
                })
        });

        const result = Joi.validate(req.body, schema, {
            abortEarly: false,
            convert: true,
            stripUnknown: true
github icodeforlove / node-cloudflare / index.js View on Github external
zoneDNSRecordNew: function ($deferred, zone_identifier, body, raw) {
		$deferred.resolve(this._request({
			params: {
				zone_identifier: Joi.string().length(32).required()
			},
			body: Joi.object({
				type: Joi.string().valid('A', 'AAAA', 'CNAME', 'TXT', 'SRV', 'LOC', 'MX', 'NS', 'SPF').required(),
				name: Joi.string().max(255).required(),
				content: Joi.string().required(),
				ttl: Joi.number().max(2147483647),
				proxied: Joi.boolean(),
				priority: Joi.number().max(65535).when('type', { is: 'MX', then: Joi.required(), otherwise: Joi.forbidden() })
			}).required()
		}, {
			callee: 'zoneDNSRecordNew',
			method: 'POST',
			path: 'zones/:zone_identifier/dns_records',
			required: 'result',
			params: {
				zone_identifier: zone_identifier
			},
			body: body
		}, raw));
	},
github microsoft / pai / src / rest-server / src / utils / manager / user / user.js View on Github external
const userSchema = Joi.object().keys({
  username: Joi.string()
    .regex(/^[\w.-]+$/, 'username')
    .required(),
  email: Joi.string()
    .email()
    .empty('')
    .default(''),
  grouplist: Joi
    .array()
    .items(Joi.string())
    .required(),
  password: Joi.string()
    .empty('')
    .default(''),
  extension: Joi.object().pattern(/\w+/, Joi.required()).required(),
}).required();

function userValidate(userValue) {
  const res = userSchema.validate(userValue);
  if (res['error']) {
    throw new Error(`User schema error\n${res['error']}`);
  }
  return res['value'];
}

function encrypt(username, password) {
  const iterations = 10000;
  const keylen = 64;
  const salt = crypto.createHash('md5').update(username).digest('hex');
  return new Promise( (res, rej) => {
    crypto.pbkdf2(password, salt, iterations, keylen, 'sha512', (err, key) => {