使用回送4,我想在我的应用程序代码中使用Typescript的类型安全性,同时从存储库装饰器中获取模式验证,但将属性存储为序列化json(在这种情况下为Postgres bson),而不是单独存储具有FK关系的实体。
考虑可能具有电话号码列表的地址簿Contact
模型:
@model()
export class PhoneNumber {
@property({ required: true })
number: string;
@property()
type: string;
}
@model()
export class Contact extends Entity {
@property({ id: true, required: true })
id: string;
@property({ required: true })
email: string;
@property({ required: true })
name: string;
@property.array(PhoneNumber)
phoneNumbers: PhoneNumber[];
constructor(data?: Partial<Contact>) {
super(data);
}
}
在上面的示例中,我获得了完整的架构验证,但是如果我尝试使用扩展了Contact
的生成的Repository
保存DefaultCrudRespository
的实例,它只会删除phoneNumbers
字段中提供的内容,并且在数据库中保存一个空列。
如果我将属性注释更改为:
@property.array(Object)
phoneNumbers: PhoneNumber[];
它将正确保存字段,序列化为json,但不会尝试验证字段,也不会在生成的openapi.json规范中将类型指定为数组PhoneNumber
似乎Loopback 3支持嵌入式模型:https://loopback.io/doc/en/lb3/Embedded-models-and-relations.html
不过,在Loopback 4文档中没有提及它。
尝试在电话号码模型中使用严格模式过滤器
@model({settings: {strict: "filter"}})
在数据库中添加时,这会使所有未知字段被忽略