API Generator
Overview
Generate APIs for HTTP requesting.
Currently use Fetch API, you may need to polyfill it yourself if needed.
Quick Start
First add meeop package to your dependencies:
npm install meeop --save
Then just import and use meeop in your client JavaScript code.
import {
apis,
registerApi,
registerApiSuccChecker,
registerHttpErrorHandler,
registerApiErrorHandler,
registerDataPreprocessor
} from 'meeop'
registerApiSuccChecker(
({ body, status }) => body && body.error_code === 0 && status === 200
)
registerApiErrorHandler(
({ body, status, apiConfig }) => {
throw new Error('API Error Detected')
}
)
registerHttpErrorHandler(
({ body, status, apiConfig }) => {
throw new Error('HTTP Error Detected')
}
)
registerDataPreprocessor(
body => body ? body.data : null
)
registerApi({
name: 'getUser',
url: '/api/v1/users/:uid',
options: {
method: 'get',
headers: {
'Cache-Control': 'no-store',
'x-black-cat': 'is-a-pretty-cat'
}
}
})
registerApi({
name: 'addUser',
url: '/api/v1/users/:uid',
options: {
method: 'post',
headers: {
'Cache-Control': 'no-store',
'x-black-cat': 'is-a-pretty-cat'
}
},
needs: {
isSuccess: 'boolean',
userId: 'number'
}
})
registerApi({
name: 'errorAddUser',
url: '/api/v1/errors/users/:uid',
options: {
method: 'post',
headers: {
'Cache-Control': 'no-store',
'x-black-cat': 'is-a-pretty-cat'
}
},
needs: {
isSuccess: 'boolean',
userId: 'number'
}
})
apis.getUser({
query: { userName: 'Jinyang', age: 3 },
params: { uid: 999 }
})
.then(data => {
console.log('getUser', data)
})
apis.addUser({
body: {
userId: 123,
isSuccess: true
},
query: { userName: 'Jinyang', age: 3 },
params: { uid: 999 }
})
.then(data => {
console.log('addUser', data)
})
apis.getUser.runWith({
apiSuccChecker: () => true
})({
query: { userName: 'Jinyang', age: 3 },
params: { uid: 999 }
})
.then(data => {
console.log('getUser - runWith', data)
})
APIs
registerApi({ name, url, options, needs })
Register a new API with given params
-
name {string}
Define name of the API, which can be accessed via apis[name]
-
url {string}
Define the target url parttern of the API.
Since there might be search query or params (like :uid
below), this url pattern will not be the final requesting url. See apis
above.
e.g. /api/v1/errors/users/:uid
.
-
options {Object}
Options of the API, default (string) value will be marked with *
:
-
cache { *default | no-cache | reload | force-cache | only-if-cached }
-
credenttials { include | same-origin | *omit }
-
headers {Object} // Customlized headers, default as {}
-
method { *GET | POST | PUT | DELETE | PATCH }
-
mode { no-cors | cors | *same-origin }
-
redirect { manual | *follow | error }
-
referrer { no-referrer | *client }
-
timeout {number}
Timeout for fetch request, default as 5000
ms
-
dataType { *JSON | URLSearchParams | FormData | Origin }
Will transform body data and set content-type header according to this field:
-
JSON: Set content-type as value application/json
, and use JSON.stringfy(body)
to serialize the body object.
-
URLSearchParams: Set content-type as value application/x-www-form-urlencoded
, and use new URLSearchParams(body)
to transform the body.
-
FormData: Set content-type as value multipart/form-data
, and use new window.FormData(body)
to transform the body.
-
Origin: Do nothing, just pass the body to fetch API.
-
needs {Object}
This field is optional
It's obvious that request with GET method doesn't need this.
API will check the validation of body data passed in, and pass through the necessary data according to this needs Object.
registerApi({
name: 'createUser',
needs: {
isVip: 'boolean',
userId: 'number',
'userName?': 'string'
}
})
apis.createUser({
body: {
isVip: true,
userName: 'Jinyang.Li'
}
})
apis.createUser({
body: {
userId: '12345',
isVip: true
}
})
apis.createUser({
body: {
userId: 12345,
isVip: true
}
})
apis.createUser({
body: {
userId: 12345,
isVip: true,
userName: 'Jinyang.Li',
otherData: 67890
}
})
apis
Object that will hold all registered APIs.
Each API is a function that will start a HTTP request and return a promise with backend data. All fields are optional.
e.g. apis[apiName]({ body, query, params })
-
body {Object}
Body will be preprocessed according to options.dataType
, checked and filtered by needs
given in registerApi
(if there has one).
-
query {Object}
Used to generate the query string of request. Here we use URLSearchParams
and you may need to polyfill it yourself.
-
params {Object}
Provide the params needed in url parttern.
registerHttpErrorHandler
Register an error handler for HTTP error. When HTTP error catched, the registered callback will be triggered.
registerApiSuccChecker
Register an function to check whether the response data is expected.
registerApiErrorHandler
Register an error handler for APIs. We consider the situation that HTTP request have a normal status while API doesn't receive the expected data as an API error. Whether the response data is expected or not is checked by apiSuccChecker
registered before.
registerDataPreprocessor
Register an function to preprocess the response body data.
api[name].runWith
We have introduced several function to register global handlers for APIs. Method runWith
allow us to generate a new API with customized handlers.
const newGetUserApi = api.getUser.runWith({
dataProcessor,
httpErrorHandler,
})
newGetUserApi({ body, params, query })