الرباعية 9: اليجرو الإيجاز والبساطة

عندما أنشأت مكتبة للتحقق من صحة البيانات quartet، اتخذت المعالم التالية:



في هذه المقالة سأوضح كيف quartetتفهم المكتبة ما تعنيه عبارة "قصير" و "بسيط" في سياق نهج التحقق من الصحة.


كيف يعمل 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