四重奏9:快板| 简洁明了

在创建用于数据验证的库时quartet,我采用了以下地标性建筑:



在本文中,我将展示库quartet在验证方法的上下文中如何理解“ Short”和“ Simple”一词的含义。


如何运作quartet


什么时候需要?需要数据验证时需要它。
什么是验证?检查数据是否合规。最常见的类型。
如何quartet帮助呢?它基于对需求的声明性描述(方案)创建验证功能。编译器功能v将电路转换为验证功能。而且v,准备好的方案和方法存储在内部以创建更复杂的方案。有关更多详细信息,请参见文档


怎么运行的?


  1. 你写一个方案
  2. 您将其提供给编译器函数的输入v以获取验证函数。
  3. 验证功能可以使用了!

让我们四方验证所有数据,而不用七种方法使大脑紧张。


.



:


type Answer = 42;

quartet:


const answerSchema = 42;

- :


import { v } from "quartet";
const checkAnswer = v(42);

. — .



, . — .


. , , .


const checkNumber = (x) => typeof x === "number";
const checkString = (x) => typeof x === "string";
const checkBoolean = (x) => typeof x === "boolean";
const checkSymbol = (x) => typeof x === "symbol";
// ...

:


const checkSomeType = x => typeof x === "<type>",  <type> –   

, :


'string'v.string
'number'v.number
'boolean'v.boolean
'symbol'v.symbol

, :


const checkNumber = v(v.number);
//  , 
const checkNumber = (x) => typeof x === "number";

quartet


'function'v.function

:


const checkFunction = v(v.function);
//  , 
const checkFunction = (x) => typeof x === "function";

. C — v..


«»


:


type NullableString = string | null;

quartet:


const nullableStringSchema = [v.string, null];

:


const checkNullableString = v([v.string, null]);

:


type VariantSchema = Schema[];

. – .


«»



type Password =  string //     8-      1   .

. v.minLength() v.test(RegExp)


const stringSchema = v.string;
const min8Schema = v.minLength(8);
const atLeastOneDigitSchema = v.test(/\d/);
const atLeastOneLetterSchema = v.test(/[A-Za-z]/);

v.and():


const passwordSchema = v.and(
    stringSchema,
    min8Schema,
    atLeastOneDigitSchema,
    atLeastOneLetterSchema,
)

. v.and(, , ...).



Person:


interface Person {
    name: string
    age: number
}

, Person?
, name age. string number. !


, , .


— !


:


const personSchema = {
  name: v.string,
  age: v.number,
};

:


interface ObjectInterfaceSchema {
  [propertyName: string]: Schema;
}

. — , — , — .



:


type Numbers = number[];

v.arrayOf(). .


const checkNumbers = v(v.arrayOf(v.number));

. v.arrayOf( ).



quartet.


. є v.custom( ):


const evenSchema = v.custom((x) => x % 2 === 0)
const evenNumberSchema = v.and(
  v.number,
  evenSchema,
);

. v.custom( ).



  • — .
  • C — v..
  • — .
  • v.and(, , ...).
  • — , — , — .
  • v.arrayOf( ).
  • v.custom( ).

P.S.


. quartet :
. 4 , .


, !


All Articles