Generate module for API requesting:
- follow CommonJS specification or ES2015
- from easy config file
- with Promise returned
- by XMLHttpRequest or fetch API (Current version use fetch API to request. Wish to use XMLHttpRequest? See tag 0.2.4)
- builtin browserify and rollup
- e.t.c
Install with this command:
npm install js-api-generator --save
or maybe you like yarn:
yarn add js-api-generator
This part is for generated module.
- Each API accepts an object param which will be sent as ajax data. The
needs
api config will be checked in this param. - Each API returns a Promise. Resolve or reject will determined by
isSuccess
api config. - Each API won't send request again before response or timeout, but callback will be queued which will all be triggered when get response or timeout.
- The callback function accepts an object param which content is determined by
success
orfail
api config. - The output module is in ES2015 syntax. You should do babel or buble yourself if you want.
var api = require('path/to/generated-api-module');
api.yourApiName({
// data to send
}).then(res => {
// res object content is determined by `success` config
// do some stuff for success
}, err => {
// err object content is determined by `fail` config
// do some stuff for fail
});
<script src="path/to/generated-api-module.js"></script>
<script>
api.yourApiName({
// data to send
}).then(res => {
// res object content is determined by `success` config
// do some stuff for success
}, err => {
// err object content is determined by `fail` config
// do some stuff for fail
});
</script>
Config file should be YAML format and should have api
and config
object.
Provide api list. Each api could have follow options:
The url for requesting. Support dynamic url which means you could use variable in url link.
If the config url is /user/:uid
and you call this API by {uid: 123}
, the request url will be /user/123
.
The global prefix should set at config.rootUrl
.
This api.rootUrl
option is used to cover that in some case.
The method name for this api in generated module.
The request method such as post
. Ignore case.
The alias for method
. [DEPRECATED]
Default: {}
If this is an array, strings in it will be used as property name to check existent and not empty in request data. [DEPRECATED]
If this is an object, the key will be used as property name and the value as variable type(or type list) for data check. Any
will be used if can't match any option. Supported variable type check list:
- String
- Number
- Boolean
- Array
- Blob
- Object
- Null
- Any
If any key is end with ?
, property name won't include the ?
and this key will be treated as optional.
Limit request timeout. Milliseconds.
The request mode for fetch API. Could be cors
, no-cors
, same-origin
, navigate
, websocket
.
The request credentials for fetch API. Could be omit
, same-origin
, include
.
The request cache for fetch API. Could be default
, no-store
, reload
, no-cache
, force-cache
, only-if-cached
.
Since the cache option only support in Firefox 48+,
the request url will be added a query string automatically like what jQuery ajax cache did when the cache value is reload
, no-cache
or no-store
.
Use to determine success or fail for requesting.
- success: response object must has same key-value pair for every key-value pair in this object
- fail: any mismatch
Use to constitute a callback param when success.
Use to constitute a callback param when fail.
Use to add custom request headers. Such as X-Requested-With
.
Use to construct data for request body. Ignore case. Origin
will be used if can't match any option. Supported type list:
Use URLSearchParams to construct passed in data. Maybe you need this polyfill for IE.
This package will set Content-Type
to application/x-www-form-urlencoded
for request header automatically since some browser don't support URLSearchParams
and they won't add that header even if you use URLSearchParams
polyfill. You could overwrite it by headers
option.
Use FormData to construct passed in data.
Browser will set Content-Type
to multipart/form-data
for request header automatically.
This option will stringify passed in data to a JSON string by JSON.stringify
.
This package will set Content-Type
to application/json
instead of text/plain
for request header automatically since browser won't do that. You could overwrite it by headers
option.
Won't do anything for passed in data and pass it through to fetch body.
Provide global options. Could have follow options:
Default: Promise
The global promise object in your environment.
Default: get
The request method such as post
. Ignore case.
For all api. Will be covered by api.type
.
The alias for method
. [DEPRECATED]
Default: default
For all api. Will be covered by api.cache
.
Default: same-origin
For all api. Will be covered by api.mode
.
Default: same-origin
For all api. Will be covered by api.credentials
.
Default: {}
For all api. Will be covered by api.isSuccess
.
Default: 5000
For all api. Will be covered by api.timeout
.
Default: []
For all api. Will be extended by api.success
.
Default: []
For all api. Will be extended by api.fail
.
Default: false
If response dose not have param which success or fail need, whether to throw an error or not.
The error message you supply will overwrite default error message by same name.
Default: { 'Accept': 'application/json, */*; q=0.01', 'Accept-Charset': 'utf-8' }
For all api. Will be extended by api.headers
.
Default: Origin
For all api. Will be covered by api.dataType
.
Default: ''
Set prefix for api.url
. For all api. Will be covered by api.rootUrl
.
api:
-
url: //www.123.com/test/test1
type: put
name: createAlgorithm
mode: 'cors'
needs:
username: String
nickname?: String
success:
- algorithmId
- updateTime
-
url: /test/test2
type: delete
name: checkLogin
cache: 'no-cache'
timeout: 10000
needs:
test: Boolean
success:
- username
- avatar
-
url: /test/test3
type: post
name: editUser
isSuccess:
status: true
needs:
username: String
id:
- Number
- String
-
url: /test/:sid/:pid
type: get
name: getPt
needs:
sid: Number
pid?: Number
config:
isSuccess:
code: 0
ignoreResponse: false
headers: {
Content-Type: application/x-www-form-urlencoded
}
fail:
- message
This part is for using this package.
The follow options are used for this package, not for yaml config.
Yaml config file path. Should be absolute path or relative to the file you run this command.
Default: english
Language for error message. Ignore case. Welcome PR >.<
- Chinese
- English
The file path to output result. Should be absolute path or relative to the file which use this package.
Default: commonjs
The output file follows the module spec you choose. Ignore case. Welcome PR to add more. Support list:
- CommonJS
- ES2015
Default: false
This option determine the output code could run in browser directly or not.
If it's not false
, it should be a string as a module name for browser global object.
The CommonJS module will be transform with browserify and ES2015 module will be transform with rollup. Then you could use generated module in browser like Generated Module Usage Example.
Default: utf8
.
File encoding for config file and output file.
var api = require('js-api-generator');
var result = api({
target: 'target yaml path',
// other options
});
Chrome | Firefox | Edge | IE | Opera | Safari | |
---|---|---|---|---|---|---|
Output file | 45.0 | 22.0 | Yes | Not support | 32 | 10.0 |
Compile with babel or buble | Yes | Yes | Yes | Depends on polyfill | Yes | Yes |
See ./test/api.yml
.