Express Rest Tools
Install
npm install express-rest-tools
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
{
0: 'Success',
1: 'Failed to fetch service',
2: 'API error',
3: 'Validation rules error',
4: 'File system error',
5: 'Application error'
}
setConfig({
reasons: {
6: 'Custom descirption',
7: 'Custom descirption'
}
})
Throw error
Use throw
to return error message
throw Object({
type: 5,
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
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
Name | Description |
---|
cache | Cache response in memory |
validate | Validate request with rules |
cache
import { cache } from 'express-rest-tools/lib/middlewares'
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: {
name: Joi.string().required(),
age: Joi.number().required()
}
}
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
router.get('/users', controller)