1.3.2 • Published 4 years ago

express-rest-tools v1.3.2

Weekly downloads
-
License
MIT
Repository
-
Last release
4 years ago

Express Rest Tools

npm version

Install

npm install express-rest-tools

Configulation

Config keyDefaultTypeDescription
port4000NumberDevelopment server port
corsOptions{}ObjectNode.js CORS middleware
loggerfalseBool, FunctionCreate log format of each activities
fetchErrorHandlerfalseBool, FunctionHandle api response that should be an error (Function must return boolean)
fetchMessageErrorHandlerfalseBool, FunctionHandle error message from api response
reasonsResons TypesObjectReason code and message
swaggerDefinition{}ObjectA document that defines or describes an API see more

Setup and config app in server.js

import { setConfig, useRouter, startServer } from 'express-rest-tools'
import routes from './routes'

const reasons = {
  6: 'Custom description',
  7: 'Custom description'
}

const fetchErrorHandler = res => {
  if (res.status !== 200) return true
  return false
}

const fetchMessageErrorHandler = res => {
  throw Object({
    type: 6,
    th: 'Message',
    en: 'Message',
    technical: 'Message'
  })
}

const logger = (type, datas) => {
  if (type === 'access') {
    return { type }
  }

  if (type === 'activity') {
    return { type }
  }

  if (type === 'response') {
    return { type }
  }

  if (type === 'error') {
    return { type }
  }
}

setConfig({
  port: 4000,
  corsOptions: {},
  reasons,
  swaggerDefinition: {},
  fetchErrorHandler,
  fetchMessageErrorHandler,
  logger
})

useRouter(routes)

startServer()

Reasons Types

// Default
{
  0: 'Success',
  1: 'Failed to fetch service',
  2: 'API error',
  3: 'Validation rules error',
  4: 'File system error',
  5: 'Application error'
}

// Add
setConfig({
  reasons: {
    6: 'Custom descirption',
    7: 'Custom descirption'
  }
})

Throw error

Use throw to return error message

throw Object({
  type: 5, // Reason code
  th: 'Message',
  en: 'Message',
  technical: 'Message'
})

Resonse json format

{
  "transactionID": "G2PC01RKZJSU42YEH-2019/03/04|15:57:44",
  "serviceResult": {
    "status": "ERROR",
    "code": 1,
    "description": "Failed to fetch service"
  },
  "message": {
    "th": "Message",
    "en": "Message",
    "technical": "Message"
  },
  "data": null
}

Server scripts

Dev server

$ npm run dev

Production server

$ npm run start

Testing

$ npm run test
$ npm run test:watch

Listing

$ npm run lint

Utilities

NameDescription
asyncHandlerSupported throw error in async function then the error will be handle by middleware
createFetcherFetching API and handle error (try/catch) under hood
useActivityLog activity

Example

Wrap controller function and use res({}) to return data

import { asyncHandler } from 'express-rest-tools/lib/utils'

const posts = asyncHandler((req, res) => {
  const postData = []
  res({
    data: postData
  })
})
res({
  headers: {},
  data: any
})

Use axios options

import { createFetcher } from 'express-rest-tools/lib/utils'

const fetchPosts = createFetcher({
  method: 'get',
  url: 'https://jsonplaceholder.typicode.com/posts'
})

const posts = await fetchPosts()

Fetch soap

import { createFetcher } from 'express-rest-tools/lib/utils'

const fetchSoapAPI = createFetcher({
  method: 'post',
  headers: {
    'Content-Type': 'text/xml;charset=UTF-8'
  },
  url: 'http://api',
  data: `xml`
})

const soap = await fetchSoapAPI()
import { useActivity } from 'express-rest-tools/lib/utils'

useActivity({ name: 'fetchPosts' })

Middlewares

NameDescription
cacheCache response in memory
validateValidate request with rules
import { cache } from 'express-rest-tools/lib/middlewares'

// cache(duration)

router.get('/posts', cache(5000, 'prefix'), controller.posts)

Clear Cache

import { clear, clearAll } from 'express-rest-tools/lib/middlewares/cache'

clear('prefix')

clearAll()
import { validate } from 'express-rest-tools/lib/middlewares'
import Joi from 'joi'

// const rules = {
//   query: {},
//   params: {},
//   body: {}
// }

const rules = {
  query: {
    name: Joi.string().required(),
    age: Joi.number().required()
  }
}

// Use a function to get request data

const rules = {
  query: req => ({
    name: Joi.string().required(),
    age: Joi.number().required()
  })
}

router.get('/posts', validate(rules), controller.posts)

Add Middlewares

import { useMiddleware } from 'express-rest-tools'

useMiddleware(yourMiddleware)

API Documentation

The Swagger UI page is https://server/api-docs

Example to write document with Swagger

/**
 * @swagger
 * /users:
 *   get:
 *     description: Returns users
 *     tags: [Users]
 *     parameters:
 *       - in: query
 *         name: "name"
 *         required: true
 *         type: "string"
 *     responses:
 *       200:
 *         description: Success
 */
router.get('/users', controller)