Parameters validation With SugoiJS request parameters validation become easier
SugoiJS server module uses @sugoi/core policies and supply predefined policies, and re-export SchemaTypes, TPolicy, TComparableSchema, Policy, UsePolicy, ComparableSchema from "@sugoi/core";
Further information on the @sugoi/core package documentation
RequestSchemaPolicy
Copy /**
* paramSchema - req.params
* queryParamSchema - req.query
* bodySchema - req.body
* headersSchema - req.headers
**/
export function RequestSchemaPolicy (paramSchema : TComparableSchema );
export function RequestSchemaPolicy (paramSchema : TComparableSchema , queryParamSchema : TComparableSchema );
export function RequestSchemaPolicy(paramSchema: TComparableSchema, queryParamSchema: TComparableSchema, bodySchema: TComparableSchema);
export function RequestSchemaPolicy(paramSchema: TComparableSchema, queryParamSchema: TComparableSchema, bodySchema: TComparableSchema, headersSchema: TComparableSchema);
The RequestSchemaPolicy
decorator use for validate the request is using a valid schema for params\queryParams\body\headers.
In case null will pass the value won't check.
Example:
Copy @ Controller ( '/dashboard' )
export class DashboardController {
constructor () {
}
@ HttpPost ( "/:id" )
@ RequestSchemaPolicy (
{ "id" : ComparableSchema .ofType ( SchemaTypes . NUMBER )} ,
null ,
{
"role" : ComparableSchema .ofType (
{
text : ComparableSchema
.ofType ( SchemaTypes . STRING )
.setRegex ( "([A-Z])+" , "i" )
}
)
}
) //body schema is {role:{text:string//with regex - /([A-Z])+/i}}
getUser (@ RequestParam ( "id" ) id : number , @ RequestBody () body : {role : {text : string }}) {
return User .findOne ({id , role : body . role .text})
}
}
Validation per parameter type
RequestParamsSchemaPolicy
For validating only the request parameters you can use RequestParamsSchemaPolicy
Copy function RequestParamsSchemaPolicy (schema : TComparableSchema )
RequestQueryParamsSchemaPolicy
For validating only the request query parameters you can useRequestQueryParamsSchemaPolicy
Copy function RequestQueryParamsSchemaPolicy (schema : TComparableSchema )
RequestBodySchemaPolicy
For validating only the request body you can useRequestBodySchemaPolicy
Copy function RequestBodySchemaPolicy (schema : TComparableSchema )
For validating only the request headers you can use RequestHeadersSchemaPolicy
Copy function RequestHeadersSchemaPolicy (schema : TComparableSchema )
Full example
Copy @ HttpPost ( "/:id" )
@ RequestParamsSchemaPolicy (RequestWithIDSchema)
@ RequestQueryParamsSchemaPolicy ({
check : ComparableSchema .ofType ( SchemaTypes . STRING ) .setMandatory ( false )
})
@ RequestBodySchemaPolicy ({
data : ComparableSchema .ofType ( SchemaTypes . STRING ) .setMandatory ( true )
})
@ RequestHeadersSchemaPolicy ({
"x-user-language" : ComparableSchema .ofType ( SchemaTypes . STRING ) .setMandatory ( true )
})
public setData (@ RequestParam ( "id" ) id: string) {
// finally the logic
}