Reputation: 326
I'm looking for a way to prevent unwanted properties to be present in the requestBody as described in the associated Model
Here is my model :
import { Model, model, property } from '@loopback/repository';
@model({
name: 'AwsS3',
strict: true,
description: 'AWS S3 Object description',
properties: {
Key: {
type: 'String',
required: 'true',
},
Bucket: {
type: 'String',
requied: 'true',
},
},
})
export class AwsS3 extends Model {
@property({
type: 'string',
description: 'path/to/file',
required: true,
}) Key: string;
@property({
type: 'string',
description: 'AWS-S3-Bucket-Name',
required: true,
})
Bucket: string;
constructor(data: AwsS3) {
super(data);
}
}
I used it like this in the controller
function(@requestBody({
required: true,
description: 'aws object settings',
content: {
'application/json': {},
},
}) body : AwsS3
){
console.log(body);
}
It throws correctly when one of both properties is missing or in the wrong type. But if i send a json like bellow nothing is thrown and object is processed with the UnwantedProp
{
Key: 'key',
Bucket : 'bucket',
UnwantedProp: 40
}
Upvotes: 1
Views: 4950
Reputation: 326
I found it to be achievable by using the @api decorator and setting the additionalProperties: false from the openapi specs.
use it like :
@api(
basePath: '/',
paths : {
'somepath': {
'post' : {
'x-operation-name': 'myfunction',
'x-controller-name': 'MyController',
// properties for route
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
additionalProperties: false, // <=== here it is
properties: {
Key: { type: 'string'},
Bucket: {type: 'string'},
},
required: ['Bucket', 'Key'],
},
},
},
},
}
}
}
)
export class MyController{
async myfunction(
@requestBody({ settings: { strict: true } }) body
){}
}
when testing it throws the following as expected :
{
"error": {
"statusCode": 422,
"name": "UnprocessableEntityError",
"message": "The request body is invalid. See error object `details` property for more info.",
"code": "VALIDATION_FAILED",
"details": [
{
"path": "",
"code": "additionalProperties",
"message": "should NOT have additional properties",
"info": {
"additionalProperty": "unwantedProp"
}
}
]
}
}
Upvotes: 2