1.1.1 • Published 3 years ago

@despel/live-reload-api v1.1.1

Weekly downloads
-
License
ISC
Repository
github
Last release
3 years ago

Simple Module for Reloading Stateless API Endpoints on File Changes

How to Use

const app = express()

const API_PATHS = [
  '/src/api',
  '/src/new_api',
]

const API_PREFIXES = [
  '/v1',
  '/v2',
]

const loadedCallback = () => {
  console.log('Endpoints loaded!')
}

const { setupAPI } = require("@despel/live-reload-api")
const reloadAPI = setupAPI(app, API_PATHS, API_PREFIXES, loadedCallback)

After saving a file inside the API_PATHS folder, the entire API will be reloaded. Creating and deleting files also updates the API.

How to create an endpoint

Endpoint URL

The file path wil determine the endpoint path, for example

  url = 'http://localhost:3434'
  apiPrefix = '/session'
  apiPath = '/api/src/session'
  filePath = '/api/src/session/users/create.js'

The resulting endpoint will be:

  url + apiPrefix + filePath.replace(apiPath, "")
  // http://localhost:3434/session/users/create

Endpoint file structure To correctly create an endpoint, the following structure is required

module.exports = {
  // optional, use at least one
  get: {
    function: (req, res) => {}, // Request handler
    middleware: [ // Middeware applied to the specific endpoint method
      (req, res, next) => {},
      //... 
    ]
  },
  post: {
    function: (req, res) => {},
    middleware: [
      (req, res, next) => {},
      //... 
    ]
  },
  put: {
    function: (req, res) => {},
    middleware: [
      (req, res, next) => {},
      //... 
    ]
  },
  delete: {
    function: (req, res) => {},
    middleware: [
      (req, res, next) => {},
      //... 
    ]
  },
  // Middleware applied to all methods
  middleware: [
    (req, res, next) => {},
    //... 
  ]
}

Middlware It is recommended to put the middleware in a different file/folder. The middleware for the endpoints is inherited from the folder structure.

If a parent folder contains a middleware.js file, the defined handlers will be applied to all children endpoints.

Middleware.js file structure

module.exports = {
  middleware: [ // Applied to all methods (general middleware).
    (req, res, next) => {},
    // ...
    (req, res, next) => {},
  ],
  get: [ // Applied only to a specific method (specific middleware).
    (req, res, next) => {},
    // ...
    (req, res, next) => {},
  ],
  //... post, put, delete
}

The order of execution of the middleware starts from the root folder and the general middleware is executed before the specificic middleware. The file middlware.js is prepended to the middleware specified in endpoint_name.js.

1.1.1

3 years ago

1.1.0

3 years ago

1.0.0

3 years ago