我在模型中定义了以下属性:
@H_404_6@@property({ type: 'string',required: true,min: 2,max: 255 }) name: string
但是,当我发送包含1个字符的字段时,并没有抛出错误.有人可以帮我吗?
以下是来自the Loopback 4 documentation的声明:
The data from request body is validated against its OpenAPI schema specification. We use AJV module to perform the validation,which validates data with a JSON schema generated from the OpenAPI schema specification.
从Open API V3 documentation我们可以看到它们支持字符串数据类型和
String length can be restricted using minLength and maxLength:
AJV support minLength and maxLength properties too,但是由于某些原因,回送4还没有一种简单的内置方法来使用@property装饰器定义这些属性.
无论如何,我发现了一种暂时可以使用的解决方法:
@H_404_6@import { Entity,model,property,Model } from '@loopback/repository'; import { getJsonSchema } from '@loopback/repository-json-schema'; @model() export class MyModel extends Model { @property({ type: 'string',}) name: string; constructor(data?: Partial<MyModel>) { super(data); } static initialize() { let jsonSchema = getJsonSchema(MyModel) as any; jsonSchema.properties.name.minLength = 2; jsonSchema.properties.name.maxLength = 255; } } MyModel.initialize();
注意,所有的魔术都发生在MyModel.initialize方法中,其中我使用标准的getJsonSchema函数(环回的一部分)初始化jsonSchema.然后,我使用其他minLength和maxLength属性扩展此jsonSchema.在getJsonSchema函数内部,它们使用json模式的缓存,因此在应用程序生命周期内为每个模型仅生成一次模式,以确保我们设置的值在以后每次请求此json模式时都保留在那里.
您还可以在Loopback Next的Github页面上查看相关问题:
> Epic: Validation at Model/ORM level
> Complex OpenAPI Validations with @property