Provides a transformation layer between models and actual API endpont responses in JSON format.
Install the package:
npm install adonis-api-resources
Configure the package:
node ace configure adonis-api-resources
Generate a new resource:
node ace make:resource user
Edit newly generated app/resources/users_resource.ts to create output you need. This example shows how you may output user's full name even if your implementation of user model has separate fields for the first and last names:
...
return {
full_name: data.firstName + ' ' + data.lastName,
}
...
Import your generated resource before using it, i.e. in a controller:
import UserResource from '#resources/user_resource'
Remove old endpoint return declaration:
return user
Use the your generated resource instead:
return new UserResource(user).refine()
You may also use arrays of models, with resources:
return new UserResource(users).refine()
That's it. Enjoy yourself!
Model:
{
"full_name": "John Doe"
}
Array of models:
[
{
"full_name": "John Doe"
},
{
"full_name": "Jane Doe"
}
]
Offset-based pagination is supported. Example usage:
const users = await User.query().paginate(1, 10)
return new UserResource(users).refine()