adonis-api-resources

1.1.0 • Public • Published

AdonisJS API resources

gh-workflow-image npm-image license-image

Description

Provides a transformation layer between models and actual API endpont responses in JSON format.

Setup

Install the package:

npm install adonis-api-resources

Configure the package:

node ace configure adonis-api-resources

Usage

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!

Expected output examples

Model:

{
  "full_name": "John Doe"
}

Array of models:

[
  {
    "full_name": "John Doe"
  },
  {
    "full_name": "Jane Doe"
  }
]

Pagination support

Offset-based pagination is supported. Example usage:

const users = await User.query().paginate(1, 10)
return new UserResource(users).refine()

Readme

Keywords

Package Sidebar

Install

npm i adonis-api-resources

Weekly Downloads

4

Version

1.1.0

License

MIT

Unpacked Size

13.4 kB

Total Files

17

Last publish

Collaborators

  • rykantas