【问题标题】:Validate Json Schema which have Dynamic Keys in Typescript验证在 Typescript 中具有动态键的 Json 模式
【发布时间】:2019-10-01 07:24:23
【问题描述】:

我有一个文件夹“模式”,其中包含不同的 JSON 文件来存储不同的模式。

例如,

/schemas/apple-schema.json

{
  "$schema": "http://json-schema.org/draft-06/schema",
  "type": "object",
  "properties": {
    "apple_name": {
      "type": "string"
    },
    "id": {
      "type": "integer"
    },
    "apple_weight": {
      "type": "number"
    },
    "timestamp": {
      "type": "string",
      "format": "date-time"
    },
    "required": ["id"]
  }
}

/schemas/mango-schema.json

{
  "$schema": "http://json-schema.org/draft-06/schema",
  "type": "object",
  "properties": {
    "mango_name": {
      "type": "string"
    },
    "id": {
      "type": "integer"
    },
    "mango_mature": {
      "type": "number"
    },
    "mango_age": {
      "type": "number"
    },
    "mango_timestamp": {
      "type": "string",
      "format": "date-time"
    },
    "required": ["id"]
  }
}

不同的模式有不同的键。我要验证的内容如下:

  1. 所有模式中的键(例如 apple_name、id、timestamp、mango_name、mango_mature、mango_age 等)遵循相同的命名约定(带有下划线的小写:“xxx”或“xxx_yyy”)。

  2. 名称中包含“时间戳”的任何键都应采用“日期时间”格式

  3. 任何架构都应该存在键“id”。 (所有模式都需要密钥“id”)

是否可以编写一个导入所有 JSON 模式并处理验证的单元测试?

【问题讨论】:

    标签: javascript json typescript unit-testing validation


    【解决方案1】:

    您需要像 Ajv 这样的 JSON Schema Validator 来在运行时进行模式验证,而不是 TypeScript 的功能。

    您可能希望为这些水果模式编写一些类型定义,以帮助您在类型安全的情况下进行编码。

    TypeScript 提供静态类型检查,它在编译时被剥离并且在运行时不存在。所以你不能在运行时检查类型。


    根据您的要求:

    1. 验证名称约定

    你可以通过正则表达式来做到这一点。

    1. 任何架构都应存在键“id”

    TypeScript 可以为您提供以下功能:

    interface Schema {
      id: number;
    }
    
    interface AppleSchema extends Schema {
      apple_name: string,
      apple_weight: number,
      // rest properties...
    }
    
    interface MongoSchema extends Schema {
      mango_name: string,
      mango_mature: number,
      // rest properties...
    }
    
    // enjoy the power of TypeScript
    export function testApple(apple: AppleSchema) {
      console.log(apple.id); // now you can access apple.id, apple.apple_name, apple.apple_weight ...
    }
    
    // even more
    export function findFruit<T extends Schema>(fruits: T[], id: number) {
        return fruits.find(fruit => fruit.id === id)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2017-08-20
      • 2019-08-05
      • 2012-05-19
      • 1970-01-01
      • 2020-11-05
      相关资源
      最近更新 更多