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
const reasons = 6: 'Custom description' 7: 'Custom description' const fetchErrorHandler = { if resstatus !== 200 return true return false} const fetchMessageErrorHandler = { throw Object type: 6 th: 'Message' en: 'Message' technical: 'Message' } const logger = { if type === 'access' return type if type === 'activity' return type if type === 'response' return type if type === 'error' return type }
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
Throw error
Use throw
to return error message
throw Object type: 5 // Reason code th: 'Message' en: 'Message' technical: 'Message'
Resonse json format
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
const posts =
createFetcher
Use axios options
const fetchPosts = const posts = await
Fetch soap
const fetchSoapAPI = const soap = await
useActivity
Middlewares
Name | Description |
---|---|
cache | Cache response in memory |
validate | Validate request with rules |
cache
// cache(duration) router
Clear Cache
validate
Using [Joi](https://www.npmjs.com/package/joi) validator for JavaScript objects. // const rules = {// query: {},// params: {},// body: {}// } const rules = query: name: Joi age: Joi // Use a function to get request data const rules = name: Joi age: Joi router
Add Middlewares
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