I'm new with loopback 4 and I really have difficulty with the documentation that is some time not up to date. I succeed to add an authentification system and a route to log in to the users. My problem is on the "/explorer" URL, I don't know how can I add example value on the request body schema of a custom route.
There is my route:
@post('/users/login', {
responses: {
'200': {
description: 'Token',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
token: {
type: 'string'
}
}
}
}
}
}
}
})
async login(
@requestBody() credentials: Credentials,
): Promise<{token: string}> {
// make sure user exist,password should be valid
const user = await this.userService.verifyCredentials(credentials);
// console.log(user);
const userProfile = await this.userService.convertToUserProfile(user);
// console.log(userProfile);
const token = await this.jwtService.generateToken(userProfile);
return Promise.resolve({token: token})
}
And I wish to add:
{
"username": "string",
"password": "string"
}
I suppose that there is a simple way to do it but I really can't find anything about it.
FYI: The loopback4 uses the route Decorator, which provides OpenAPI specification to describe the endpoint. There is en-detailed about OpenAPI decorator in loopbac4 here.
Now to solve the above issue. lets create:
Schema for User Login i.e {"username":string, "password":string} in the schema definition you can also add the validation rules.
const UserLoginSchema = {
type: 'object',
required: ['email', 'password'],
properties: {
username: {
type: 'string',
},
password: {
type: 'string',
},
},
}; ```
Now lets quickly create your RequestBody c'tor for login. Remember as per OpenApi Specification the request body would contain description, required and content.
export const UserLoginRequestBody = {
description: 'Required input for login',
required: true,
content: {
'application/json': {schema: UserLoginSchema},
},
};
async login(
@requestBody(UserLoginRequestBody) credentials: Credentials,
): Promise<{token: string}> {
..restCode
Thats get you done.