Skip to content

Parse string in yaml format into Joi validator.

License

Notifications You must be signed in to change notification settings

alitajs/yaml-joi

Repository files navigation

yaml-joi

Alita NPM version NPM downloads Build Status Coverage Status License

Parse string in yaml format into Joi validator.

Install

$ npm install yaml-joi
or
$ yarn add yaml-joi

Example

import yamlToJoi from 'yaml-joi';

const yamlLoadOpts = {};
const yamlSchema = `
type: string
allowEmpty: true
limitation:
  - min: 3
  - max: 5
  - regex: !!js/regexp /^(\S*)$/
`;

const validator = yamlToJoi(yamlSchema, yamlLoadOpts);
validator.validate(null).error === null;
validator.validate('a').error !== null;
validator.validate('abc').error === null;
validator.validate('a b c').error !== null;
validator.validate('abcdef').error !== null;
import yamlToJoi from 'yaml-joi';

const yamlSchema = `
type: object
limitation:
  - keys:
      name:
        isSchema: true
        type: string
        allowEmpty: nothing
        limitation:
          - min: 5
          - max: 24
`;

const validator = yamlToJoi(yamlSchema);
validator.validate({}).error === null;
validator.validate({ name: 'str' }).error !== null;
validator.validate({ name: 'Alita' }).error === null;

Get more at cases.yml.

Used for model definition

export const DefineChat: DefineModel<Chat> = {
  Attr: {
    chatId: {
      type: CHAR(22),
      allowNull: false,
    },
    ...
  },
  Sample: {
    chatId: 'abcdefghijklmnopqrstuv',
    ...
  },
  Validator: yamlJoi(`
    type: object
    isSchema: true
    limitation:
      - keys:
          chatId:
            type: string
            isSchema: true
            limitation:
              - length: 22
              - token: []
          ...
export function validate<T>(instance: T, validator: Schema): T {
  const { error, value } = validator.validate(instance);
  if (error) throw error;
  return value;
}

export function validateModel<T>(define: DefineModel<T>, attrs: Partial<T>): T {
  return validate({ ...define.Sample, ...attrs }, define.Validator);
}

export function validateAttr<T, U>(define: DefineModel<T>, attrs: U): U {
  return pick(validateModel(define, attrs), ...Object.keys(attrs)) as U;
}
export default class ChatService extends Service {
  ...
  public getAllAccountChats(accountId: string) {
    const where = validateAttr(DefineChat, { accountId });
    return this.ctx.model.Chat.findAll({ where });
  }
  ...
}

Releases

No releases published

Packages

No packages published