/herbs2rest

Create a REST API based on HerbsJS

Primary LanguageJavaScriptMIT LicenseMIT

Buildcodecov

herbs2rest

Create a REST API based on herbs entities (gotu) and usecases (buchu).

Installing

    $ npm install @herbsjs/herbs2rest

Using

Use the method generateRoutes to generate api rest routes based on usecases.

herbs2rest works with express in version 4.x.

Herbarium

The default method needs a list of controllers returned by the generateControllers function using Herbarium.

Controller List

The advanced method needs a list of controllers like the example below:

const controllerList = [
  {
    name: 'lists',
    getAll: { usecase: require('../usecases/getLists'), controller: require('../controller') },
    getById: { usecase: require('../usecases/getLists'), id: 'listId' },
    post: { usecase: require('../usecases/createList') },
    put: { usecase: require('../usecases/updateList') },
    delete: { usecase: require('../usecases/deleteList') }
  }
]

The name field is the name of the route.

The id field is a string representing the id field in the use case request and can be used for GetById, Put and Delete. If you want to declare the id name dynamically with the entity field id, you need to declare the "entity.id" property in your controller list. The default value is "id". See the example below:

    const controllers = entities.map(entity => {
        const usecases = findUsecases(entity.id)
        const controllers = { name: entity.group, entity: entity.id }
        if (usecases.getAll) controllers.getAll = { usecase: usecases.getAll }
        ...
        return controllers
    })

The controller field is to replace the default controller.

The other fields refer to http methods using usecases (GetAll, GetById, Post, Put and Delete).

Custom Controller

To create a custom controller, it is necessary to follow this pattern.

const controller = async (usecase, req, user, res, next) => {
  // Implementation
}

Each method parameter has different data:

  • usecase: usecase in (buchu) pattern.
  • req: body, query and params of route.
  • user: parameter passed in the request.
  • res: response object of express.
  • next: allows the next queued route handler/middleware to handle the request.

Generate Routes with Herbarium

If you already use Herbarium, a centralized and standardized repository and discovery service for Herbs objects, you can automatically generate and use new express routes:

const express = require('express')
const { herbarium } = require('@herbsjs/herbarium')
const { generateControllers, generateRoutes } = require('@herbsjs/herbs2rest')

const app = express()
const routes = new express.Router()
const controllers = generateControllers(herbarium)

generateRoutes(controllers, routes, true)  // true = console info endpoints

app.use(routes)

Generate Routes (Advanced)

Generating and using new express routes:

const express = require('express')
const { generateRoutes } = require('@herbsjs/herbs2rest')

const app = express()
const routes = new express.Router()

generateRoutes(controllerList, routes, true)  // true = console info endpoints

app.use(routes)

HTTP Status Code and Err

Herbs2rest translates Herbs Known Errors​ to HTTP status code as described in the documentation.

Authorization

All use cases must implement the authorization method and receive a user for authentication if using the default controller.

Example:

const { Ok, Err, usecase } = require('@herbsjs/buchu')

const testUseCase = (injection) =>
  usecase('Test UseCase', {
    authorize: async (user) => {
      if (user === 'admin')
        return Ok()
      else
        return Err('Invalid user')
    }
  })

Example

Additionally you can view a simple demo application of this library in todolist-on-herbs.

How to contribute

If you would like to help contribute to this repository, please see CONTRIBUTING


License