[英]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 的值,因為String
和Number
是函數,因此不可序列化。
例如,也許您想測試特定字符串的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.