Socket
Socket
Sign inDemoInstall

express-rest-tools

Package Overview
Dependencies
380
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    express-rest-tools

[![npm version](https://badge.fury.io/js/express-rest-tools.svg)](https://badge.fury.io/js/express-rest-tools)


Version published
Weekly downloads
12
increased by1100%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

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
asyncHandler

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
})
createFetcher

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()
useActivity
import { useActivity } from 'express-rest-tools/lib/utils'

useActivity({ name: 'fetchPosts' })

Middlewares

NameDescription
cacheCache response in memory
validateValidate request with rules
cache
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()
validate Using [Joi](https://www.npmjs.com/package/joi) validator for JavaScript objects.
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)

Keywords

FAQs

Last updated on 10 Apr 2020

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc