简体   繁体   English

接口的 Json 模式 - 序列化缺少一些字段

[英]Json schema of interface - serialization missing some fields

For this code, where I have an user defined interface and schema definition is guided.对于这段代码,我有一个用户定义的界面和模式定义被引导。

type SchemaDefinition<T> = {
  [K in keyof T]: {
    type: { new(): unknown } //
    required?: boolean
  }
}

class Schema<T> {
  constructor(public schema: SchemaDefinition<T>) {}

  validate(obj: T): boolean {
    for (const prop of Object.keys(this.schema) as (keyof T)[]) {
      if (!(obj[prop] instanceof this.schema[prop].type)) return false
      if (this.schema[prop].required && obj[prop] == null) return false
    }

    return true
  }
}

interface IUser {
  name: string;
  email: string;
}

There are two schemas here.这里有两种模式。 1. for programming language specific container that is IUser interface 2. the one that I want to send it to backend that is composed by Schema object something like 1. 用于编程语言特定容器,即 IUser 接口 2. 我想将其发送到由 Schema 对象组成的后端的容器,例如

new Schema<IUser>('users',
            {
                name: {type: Number, required: true},
                email: {type: String, required: true},
            });

now I am trying to serialize this Schema object to string using JSON.stringify() but type is skipped, how can I have it serialized or how can I translate this IUser into JSON schema in the best way in TS.现在我正在尝试使用JSON.stringify()将此 Schema 对象序列化为字符串,但type被跳过,我怎样才能将其序列化,或者如何在 TS 中以最佳方式将此IUser转换为 JSON 模式。

Edit:编辑:

I was able to retrieve the type name by doing something like this我可以通过这样做来检索类型名称

const schemaRepresentation = {};
schemaRepresentation['title'] = this._name;
schemaRepresentation['additionalProperties'] = false;
schemaRepresentation['additionalProperties'] = false;

const properties = {};

for (const schemaKey in this.schema) {
  properties[schemaKey.toString()] = this.schema[schemaKey].datatype.name;
}

schemaRepresentation['properties'] = properties

if there is an array field in the interface - how do I get the type of the array?如果接口中有一个数组字段 - 我如何获取数组的类型?

You just need to use values that are serializable to JSON because String and Number are functions, and therefore are not serializable.您只需要使用可序列化为 JSON 的值,因为StringNumber是函数,因此不可序列化。

For example, maybe you want to test the typeof obj[prop] for particular string.例如,也许您想测试特定字符串的typeof obj[prop]

type AllowedTypeNames = 'string' | 'number' | 'boolean'

type SchemaDefinition<T> = {
  [K in keyof T]: {
    type: AllowedTypeNames
    required?: boolean
  }
}

And validate would now look like: validate现在看起来像:

  validate(obj: T): boolean {
    for (const prop of Object.keys(this.schema) as (keyof T)[]) {
      if (typeof obj[prop] !== this.schema[prop].type) return false
      // ^ check if the typeof the obj[prop] matches the schema.

      if (this.schema[prop].required && obj[prop] == null) return false
      // ^ check if the typeof the obj[prop] is required and present.
    }

    return true
  }

Which serializes fine:哪个序列化很好:

const userSchema = new Schema<IUser>({
  name: { type: 'string', required: true },
  email: { type: 'string', required: true },
});

console.log(JSON.stringify(userSchema.schema))
// {"name":{"type":"string","required":true},"email":{"type":"string","required":true}}

See playground 看游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM