0.2.9 • Published 5 years ago

validator-picker v0.2.9

Weekly downloads
1
License
MIT
Repository
github
Last release
5 years ago

NPM version Coverage Status

Validator And Pickers

Install

npm install validator-picker

Modules

types.js
parameter.js
type_picker.js 
deep_picker.js
regex_picker.js

Usage

types

typenote
nullaccept null
booleanbase on lodash.isBoolean.
boolextend boolean, auto parser "true", "false" ignore case.
stringbase on lodash.isString.
strextend string, auto trim and check length > 0
numberbase on !Number.isNaN && lodash.isNumber && Number.isFinite.
numextend number, auto parser string by Number
integerbase on Number.isInteger.
intextend integer, auto parser string by Number
arraybase on Array.isArray.
arrextend array, auto parser string like '1,2,3' by split(',')
objectbase on lodash.isObject && !Array.isArray.
objextend object, auto parser json string '{"name":"Tom"}' by JSON.parse
jsonpass JSON.parse
hextest by regex /^[0-9a-f]+$/i
mongoIdextend hex, check length === 24
md5extend hex, check length === 32
sha1extend hex, check length === 40
sha256extend hex, check length === 96
sha512extend hex, check length === 128
base64extend string, base on validator.isBase64
jwtbase on validator.isJWT
uuidbase on validator.isUUID
ipbase on validator.isIP
urlbase on validator.isURL
uribase on validator.isDataURI
magnetbase on validator.isMagnetURI
emailbase on validator.isEmail
const TYPES = require('validator-picker/types');
// const { TYPES } = require('validator-picker');

console.log(TYPES.number(1)); // 1

// TYPES.number('string') throw Error
  • extend your own type
const TYPES = require('validator-picker/types');

console.log(TYPES.type instanceof TYPES.Type); // true
console.log(TYPES.int instanceof TYPES.Type); // true
console.log(TYPES.int instanceof TYPES.type); // false
// extend type base on TYPES.num
TYPES.positive = TYPES.num.extend(v => v > 0);

// extend type base on TYPES.string use parse front
TYPES.true = TYPES.string.parse(v => v.toLowerCase()).extend(v => v === 'true');

console.log(TYPES.positive(1)); // true
// console.log(TYPES.positive(0)); // throw Error
console.log(TYPES.true('TrUe')); // true
// console.log(TYPES.true('False')); // throw Error
// parse and extend order
TYPES.x = TYPES.type
  .parse(v => {
    console.log('p1');
    return `p1(${v})`;
  })
  .extend(() => {
    console.log('e1');
    return true;
  })
  .parse(v => {
    console.log('p2');
    return `p2(${v})`;
  })
  .extend(() => {
    console.log('e2');
    return true;
  });

/*
p2
p1
e1
e2
 */
console.log(TYPES.x('A')); // p1(p2(A))

more example

parameter

const TYPES = require('validator-picker/types');
const parameter = require('validator-picker/parameter');
// const { TYPES, parameter } = require('validator-picker');

// extend your own type
TYPES.positive = TYPES.num.extend(v => v > 0);

const ctx = {
  params: {
    id: '00000000-0000-0000-0000-000000000000',
  },
  header: {
    endpoint: 'http://www.google.com',
    callback: null,
  },
  body: {
    user: '{"name":" Tom ","scores":"100,20,30,40"}',
    data: Buffer.from('1234567890'),
  },
};

const picker = parameter({
  id: { path: 'params', type: 'uuid', required: true },
  page: { path: 'query', type: TYPES.int, default: 1 },
  page_size: {
    path: 'query', type: 'positive', default: 10,
    'page size range': v => 1 <= v && v <= 100,
  },
  skip: { default: data => (data.page - 1) * data.page_size },

  endpoint: { path: 'header', type: [ 'url', 'null' ], required: true },
  callback: { path: 'header', type: [ 'url', 'null' ], required: true },

  user: { path: 'body', type: 'obj' },
  'user.scores': { type: TYPES.arr.each(TYPES.int) },
  data: { path: 'body', type: 'buffer' },
});

const ret = picker(ctx);
console.log(ret);

/*
{ id: '00000000-0000-0000-0000-000000000000',
  page: 1,
  page_size: 10,
  skip: 0,
  endpoint: 'http://www.google.com',
  callback: null,
  user: { name: ' Tom ', scores: [ 100, 20, 30, 40 ] },
  data: <Buffer 31 32 33 34 35 36 37 38 39 30> }
*/

more example

typePicker

通常用于输出数据前, 对返回值的域范围和类型进行过滤和限定.
It is usually used to filter and qualify the field scope and type of the return value before output data.

  • Types
typenote
trueaccept any type
falsedrop any type
nullaccept null type only
Booleanbase on lodash.isBoolean.
Numberbase on lodash.isNumber.
Stringbase on lodash.isString.
Datebase on lodash.isDate.
Bufferbase on lodash.isBuffer (not include ArrayBuffer).
Arraybase on Array.isArray, priority is higher than Object (array is object too).
Objectbase on lodash.isObject.
...recursion usage, define a array element type. only support one defined schema.
{...}recursion usage
  • Example user object
const user = {
  name: 'Tom',
  age: 22,
  adult: true,
  cash: null,
  birthday: new Date('2000-01-01'),
  file: Buffer.from('62E2'),
  education: [
    {
      city: 'Shanghai',
      school: 'No.1 high school',
      score: null,
    },
    {
      city: 'Beijing',
      school: 'Beijing University',
      gpa: 100.0,
    },
  ],
  parent: {
    mom: 'Anny',
    dad: 'King',
  },
};
  • Sample example
const typePicker = require('validator-picker/type_picker');
// const { typePicker } = require('validator-picker');

const samplePicker = typePicker({
  name: String,
  age: Number,
});

console.log(samplePicker(user));
// { name: 'Tom', age: 18 }

返回结果的域顺序与定义 samplePicker 时相同.
there returned fields order is same as when samplePicker defined.

  • Complex example
const detailedPicker = typePicker({
  name: String,
  age: Number,
  sex: String,
  birthday: Date,
  education: [
    {
      city: String,
      gpa: Number,
    },
  ],
});

console.log(detailedPicker(user));
/*
{
  "name": "Tom",
  "age": 22,
  "sex": "male",
  "birthday": "2000-01-01T00:00:00.000Z",
  "education": [
    {
      "city": "Shanghai"
    },
    {
      "city": "Beijing",
      "gpa": 100
    }
  ]
}
 */

类型不符合定义的域将不会被输出, 如 score 为 null 输出时被过滤.
Fields whose types do not match the definition will not be output, as you see when score is null it is not been output.

more example

deepPicker

用于从将复杂结构的数据中提取除部分信息.
Used to extract partial information from data in a complex structure.

  • Example date
const data = {
  body: {
    Country: {
      State: {
        Name: 'HeBei',
        Cities: [
          { Name: 'BaoDing', ParticulateMatter: [10, 200] },
          { Name: 'ShiJiaZhuang', ParticulateMatter: [50, 400] },
        ],
      },
    },
  },
};
  • use as a function
const deepPicker = require('validator-picker/deep_picker');

const picker = deepPicker('body', {
  name: 'Country.State.Name',
  city: deepPicker('Country.State.Cities', {
    name: 'Name',
    pm_2: 'ParticulateMatter[0]',
    pm_10: 'ParticulateMatter[1]',
  }),
});

console.log(picker(data));
/*
{ name: 'HeBei',
  city: 
   [ { name: 'BaoDing', pm_2: 10, pm_10: 200 },
     { name: 'ShiJiaZhuang', pm_2: 50, pm_10: 400 } ] }
 */
  • use schema to implement the same function
const deepPicker = require('validator-picker/deep_picker');

// use '$' field to set the path of rest elements
const picker = deepPicker.compile({
  $: 'body',
  name: 'Country.State.Name',
  city: {
    $: 'Country.State.Cities',
    name: 'Name',
    pm_2: 'ParticulateMatter[0]',
    pm_10: 'ParticulateMatter[1]',
  },
});

console.log(picker(data));
/*
{ name: 'HeBei',
  city: 
   [ { name: 'BaoDing', pm_2: 10, pm_10: 200 },
     { name: 'ShiJiaZhuang', pm_2: 50, pm_10: 400 } ] }
 */

more example

regexPicker

用于更方便的从正则表达式中获取所需的域.
To make it easier to get the required fields from regular expressions.

  • Example
const regexPicker = require('validator-picker/regex_picker');

const picker = regexPicker(
  /nation-(\w+)(\.(municipality|state)-(\w+))?(\.city-(\w+))?/,
  ['nationName', ['stateType', 'stateName'], ['cityName']],
);

正则表达式: /nation-(\w+)(\.(municipality|state)-(\w+))?(\.city-(\w+))?/
将由()包含的结构简化: (nationName)((stateType)(stateName))((cityName))
写为提取域: ['nationName', ['stateType', 'stateName'], ['cityName']]

console.log(picker('it is not match to regex'));
// []

console.log(picker('nation-china.city-beijing'));
/*
[ { nationName: 'china', cityName: 'beijing' } ]
 */

console.log(picker('nation-china.state-hebei'));
/*
[ { nationName: 'china', stateType: 'state', stateName: 'hebei' } ]
 */

console.log(picker('nation-china.municipality-xinjiang.city-wulumuqi'));
/*
[ { nationName: 'china',
    stateType: 'municipality',
    stateName: 'xinjiang',
    cityName: 'wulumuqi' } ]
 */

console.log(picker('nation-china.city-beijing && nation-china.state-hebei'));
/*
[ { nationName: 'china', cityName: 'beijing' } ]
*/

// 进行全局查找
console.log(picker('nation-china.city-beijing && nation-china.state-hebei', 'g'));
/*
[ { nationName: 'china', cityName: 'beijing' },
  { nationName: 'china', stateType: 'state', stateName: 'hebei' } ]
 */

more example

0.2.9

5 years ago

0.2.8

5 years ago

0.2.7

5 years ago

0.2.6

5 years ago

0.2.5

5 years ago

0.2.4

5 years ago

0.2.3

5 years ago

0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago

0.0.9

5 years ago

0.0.8

5 years ago

0.0.7

5 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago