express-rest-tools
v1.3.2
Published
[![npm version](https://badge.fury.io/js/express-rest-tools.svg)](https://badge.fury.io/js/express-rest-tools)
Downloads
14
Maintainers
Readme
Express Rest Tools
Install
npm install express-rest-tools
- Configulation
- Throw error
- Resonse json format
- Sever scrips
- Utilities
- Middlewares
- API Documentation with swagger
Configulation
| Config key | Default | Type | Description | | ------------------------ | ------------------------------ | -------------- | ----------------------------------------------------------------------------------------------------- | | port | 4000 | Number | Development server port | | corsOptions | {} | Object | Node.js CORS middleware | | logger | false | Bool, Function | Create log format of each activities | | fetchErrorHandler | false | Bool, Function | Handle api response that should be an error (Function must return boolean) | | fetchMessageErrorHandler | false | Bool, Function | Handle error message from api response | | reasons | Resons Types | Object | Reason code and message | | swaggerDefinition | {} | Object | A 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
| Name | Description | | ------------- | ----------------------------------------------------------------------------------- | | asyncHandler | Supported throw error in async function then the error will be handle by middleware | | createFetcher | Fetching API and handle error (try/catch) under hood | | useActivity | Log 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
| Name | Description | | -------- | --------------------------- | | cache | Cache response in memory | | validate | Validate 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)