繁体   English   中英

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

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

对于这段代码,我有一个用户定义的界面和模式定义被引导。

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;
}

这里有两种模式。 1. 用于编程语言特定容器,即 IUser 接口 2. 我想将其发送到由 Schema 对象组成的后端的容器,例如

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

现在我正在尝试使用JSON.stringify()将此 Schema 对象序列化为字符串,但type被跳过,我怎样才能将其序列化,或者如何在 TS 中以最佳方式将此IUser转换为 JSON 模式。

编辑:

我可以通过这样做来检索类型名称

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

如果接口中有一个数组字段 - 我如何获取数组的类型?

您只需要使用可序列化为 JSON 的值,因为StringNumber是函数,因此不可序列化。

例如,也许您想测试特定字符串的typeof obj[prop]

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

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

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
  }

哪个序列化很好:

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}}

看游乐场

暂无
暂无

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

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