【问题标题】:how to use mongo schema validation with typescript in meteor?如何在流星中使用带有打字稿的mongo模式验证?
【发布时间】:2016-09-21 06:40:52
【问题描述】:

在使用 Typescript 时,Meteor 1.3 中是否有使用模式验证的包。 Meteor 指南中推荐的包(aldeed:simple-schema)似乎没有定义文件。

那么改用什么,或者 Typescript 有一个内置的方法可以做到这一点?

【问题讨论】:

    标签: node.js mongodb meteor typescript database-schema


    【解决方案1】:

    用于 Meteor 1.3 及更高版本的 Typescript 的最佳包是 aldeed:node-simple-schema

    来自文档:

    SimpleSchema 的历史

    SimpleSchema 于 2013 年年中首次作为 Meteor 包发布。 1.0 版于 2014 年 9 月发布。2016 年年中,2.0 版 以 NPM 包的形式发布,可用于 Meteor、NodeJS、 或静态浏览器应用程序。

    安装

    npm install simpl-schema 还有其他命名的 NPM 包 简单模式和简单模式。确保安装正确 包裹。 “simpl”上没有“e”。

    所以 Typescript 中的正确导入如下所示:

    import SimpleSchema from 'simpl-schema';
    

    但是你的问题是关于打字的。 Meteor 打字的起点是 https://github.com/meteor-typescript/meteor-typescript-libs/tree/master/definitions 的 Meteor 打字库。
    在其中,您会找到 collection2 和 simple-schema 的定义,但它是 old simple-schema。它们确实为您提供了一个很好的起点,并且您会想稍后再回来拿起 collection2 的。最终,经过大约一周的搜索/等。我根据 Meteor Git 上的原件编写了自己的集合。希望它们对未来的搜索者有所帮助,即使它们对您来说有点晚了。

    declare module "simpl-schema" {
    
    export class ValidationContext {
        constructor(ss: any);
        addValidationErrors(errors: any): void;
        clean(...args: any[]): any;
        getErrorForKey(key: any, ...args: any[]): any;
        isValid(): any;
        keyErrorMessage(key: any, ...args: any[]): any;
        keyIsInvalid(key: any, ...args: any[]): any;
        reset(): void;
        setValidationErrors(errors: any): void;
        validate(obj: any, ...args: any[]): any;
        validationErrors(): any;
    }
    
    interface SchemaDefinition {
        type: any;
        label?: string | Function;
        optional?: boolean | Function;
        min?: number | boolean | Date | Function;
        max?: number | boolean | Date | Function;
        minCount?: number | Function;
        maxCount?: number | Function;
        allowedValues?: any[] | Function;
        decimal?: boolean;
        exclusiveMax?: boolean;
        exclusiveMin?: boolean;
        regEx?: RegExp | RegExp[];
        custom?: Function;
        blackbox?: boolean;
        autoValue?: Function;
        defaultValue?: any;
        trim?: boolean;
    }
    
    interface CleanOption {
      filter?: boolean;
      autoConvert?: boolean;
      removeEmptyStrings?: boolean;
      trimStrings?: boolean;
      getAutoValues?: boolean;
      isModifier?: boolean;
      extendAutoValueContext?: boolean;
    }
    
    interface SimpleSchemaStatic {
      new(schema: {[key: string]: SchemaDefinition} | any[]): SimpleSchemaStatic;
      debug: boolean;
      namedContext(name?: string): SimpleSchemaValidationContextStatic;
      addValidator(validator: Function): any;
      pick(...fields: string[]): SimpleSchemaStatic;
      omit(...fields: string[]): SimpleSchemaStatic;
      clean(doc: any, options?: CleanOption): any;
      schema(key?: string): SchemaDefinition | SchemaDefinition[];
      getDefinition(key: string, propList?: any, functionContext?: any): any;
      keyIsInBlackBox(key: string): boolean;
      labels(labels: {[key: string]: string}): void;
      label(key: any): any;
      Integer: RegExp;
      messages(messages: any): void;
      messageForError(type: any, key: any, def: any, value: any): string;
      allowsKey(key: any): string;
      newContext(): SimpleSchemaValidationContextStatic;
      objectKeys(keyPrefix: any): any[];
      validate(obj: any, options?: ValidationOption): void;
      validator(options: ValidationOption): Function;
      RegEx: {
          Email: RegExp;
          EmailWithTLD: RegExp;
          Domain: RegExp;
          WeakDomain: RegExp;
          IP: RegExp;
          IPv4: RegExp;
          IPv6: RegExp;
          Url: RegExp;
          Id: RegExp;
          ZipCode: RegExp;
          Phone: RegExp;
      };
    }
    
    interface ValidationOption {
        modifier?: boolean;
        upsert?: boolean;
        clean?: boolean;
        filter?: boolean;
        upsertextendedCustomContext?: boolean;
    }
    
    interface SimpleSchemaValidationContextStatic {
        validate(obj: any, options?: ValidationOption): boolean;
        validateOne(doc: any, keyName: string, options?: ValidationOption): boolean;
        resetValidation(): void;
        isValid(): boolean;
        invalidKeys(): { name: string; type: string; value?: any; }[];
        addInvalidKeys(errors: { name: string, type: string; }[]): void;
        keyIsInvalid(name: any): boolean;
        keyErrorMessage(name: any): string;
        getErrorObject(): any;
    }
    
    interface MongoObjectStatic {
        forEachNode(func: Function, options?: {endPointsOnly: boolean;}): void;
        getValueForPosition(position: string): any;
        setValueForPosition(position: string, value: any): void;
        removeValueForPosition(position: string): void;
        getKeyForPosition(position: string): any;
        getGenericKeyForPosition(position: string): any;
        getInfoForKey(key: string): any;
        getPositionForKey(key: string): string;
        getPositionsForGenericKey(key: string): string[];
        getValueForKey(key: string): any;
        addKey(key: string, val: any, op: string): any;
        removeGenericKeys(keys: string[]): void;
        removeGenericKey(key: string): void;
        removeKey(key: string): void;
        removeKeys(keys: string[]): void;
        filterGenericKeys(test: Function): void;
        setValueForKey(key: string, val: any): void;
        setValueForGenericKey(key: string, val: any): void;
        getObject(): any;
        getFlatObject(options?: {keepArrays?: boolean}): any;
        affectsKey(key: string): any;
        affectsGenericKey(key: string): any;
        affectsGenericKeyImplicit(key: string): any;
    }
    
    export const SimpleSchema: SimpleSchemaStatic;
    export const SimpleSchemaValidationContext: SimpleSchemaValidationContextStatic;
    export const MongoObject: MongoObjectStatic;
    
    export interface SimpleSchema {
      debug: boolean;
      addValidator(validator: Function): any;
      extendOptions(options: {[key: string]: any}): void;
      messages(messages: any): void;
      RegEx: {
          Email: RegExp;
          Domain: RegExp;
          WeakDomain: RegExp;
          IP: RegExp;
          IPv4: RegExp;
          IPv6: RegExp;
          Url: RegExp;
          Id: RegExp;
          ZipCode: RegExp;
          Phone: RegExp;
      };
    }
    
    export interface MongoObject {
      expandKey(val: any, key: string, obj: any): void;
    }
    
    export default SimpleSchema;
    }
    

    这是基于截至 2017 年 4 月 23 日的最新版本。

    对于奖励积分,这是验证方法的集合,您将在接下来寻找它:

    declare module "meteor/mdg:validated-method" {
        declare class ValidatedMethod<T> extends MeteorValidatedMethod.ValidatedMethod<T> { }
    
        declare module MeteorValidatedMethod {
            export class ValidatedMethod<T> {
                constructor(options: ValidatedMethodOptions<T>);
                call(options?: T, cb?: (err, res)=> void): void;
            }
    
            interface ValidatedMethodOptions<T> {
                name: string;
                mixins?: Function[];
                validate: any;
                applyOptions: any;
                run(opts: T);
            }
        }
    }
    

    对于在 Meteor 世界中开始研究模式和验证的搜索者,这里还有一些模块可以帮助您完善验证包:

    aldeed:collection2-core       2.0.0  Core package for aldeed:collection2
    aldeed:schema-deny            2.0.0  Deny inserting or updating certain properties through schema options
    aldeed:schema-index           2.0.0  Control some MongoDB indexing with schema options
    mdg:validated-method          1.1.0  A simple wrapper for Meteor.methods
    mdg:validation-error          0.5.1  A standard validation error to be used by form/method/validation packages
    

    【讨论】:

    • 由于速记定义和数组项定义引发类型错误,在SimpleSchemaStatic,我将构造函数更改为:new(schema: {[key: string]: SchemaDefinition | any } | any[]): SimpleSchemaStatic;。此外,validator() 参数是可选的:validator(options?: ValidationOption): Function;
    猜你喜欢
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 2020-08-15
    • 2018-06-15
    • 1970-01-01
    • 2021-11-22
    相关资源
    最近更新 更多