Provides a transformation layer between a model and the actual API endpoint response in JSON format.
Install the package:
npm install adonis-api-resources
Configure the package:
node ace configure adonis-api-resources
Generate a new resource (e.g., for a User
model):
node ace make:resource user
Import the generated resource before using it, for example in a controller:
import UserResource from '#resources/user_resource'
Remove the old endpoint return declaration:
return user
Use the generated resource instead:
return new UserResource(user).remap()
remap()
modifies a model or an array of models according to the custom map defined in the resource file.
Edit the newly generated app/resources/user_resource.ts
file to produce the output you need. This example shows how you can output the user's full name, even if your User
model has separate fields for the first and last names.
...
return {
full_name: data.firstName + ' ' + data.lastName,
}
...
You can also use arrays of models with resources:
return new UserResource(users).remap()
Model:
{
"full_name": "John Doe"
}
Array of models:
[
{
"full_name": "John Doe"
},
{
"full_name": "Jane Doe"
}
]
No map definition is needed if you only want to pick a few values from the object and leave the rest out.
Example:
return new UserResource(users).pick('email', 'firstName', 'lastName')
No map definition is needed if you only want to exclude a few values from the object.
Example:
return new UserResource(users).omit('createdAt', 'updatedAt')
If you are dealing with a non-paginated array, you can still create pagination using this extension.
See examples below:
return new UserResource(users).remap().paginate(page, limit)
return new UserResource(users).pick('email', 'firstName', 'lastName').paginate(page)
return new UserResource(users).omit('id', 'password').paginate()
- page — Number of the page to show (optional, default: 1)
- limit — Items per page (optional, default: 10)
Do not use paginate()
on a collection that has already been paginated. If the collection is paginated by an ORM or ODM, this extension will only forward the original pagination metadata to the endpoint without altering it.
Offset-based pagination is supported for Lucid and MongoDB ODM for AdonisJS