dalao-proxy v1.0.0-beta.25
Dalao-proxy
An expandable HTTP proxy based on the plug-in system for frontend developers with request caching request mock and development!
An one-line command server! More light-weight and convenient than the proxy of
webpack-dev-serverin daily development.
Features
- HTTP proxy
- HTTP capture
- Request mock
- Request auto cache with flexible configuration
- Auto-generate config file
- Auto reload server when config file changes
- Support fast switching of multiple environments
- Expandable and plugin-based system

Table of contents
Getting Started
Install
$ npm i dalao-proxy -gConfigure
Default configuration file will be generated in dalao.config.json.
# This utility will walk you through creating a config file
$ dalao-proxy init
# Generate config file directly
$ dalao-proxy init -yStart proxy
# dalao will read default config file
$ dalao-proxy start
# custom options
dalao-proxy start -wc --config ./dalao.config.jsonStart Options
Options:
-C, --config [filepath] use custom config file
-w, --watch reload when config file changes
-P, --port [port] custom proxy port
-H, --host [hostname] dynamic add host linked to your server address
-t, --target [proxyTarget] target server to proxy
-c, --cache enable request cache
-i, --logger enable log print
-h, --help output usage information🎉 Congratulations, your one-line command proxy server started, now you have your own dalao!
Enjoy it!
Every single modification of the configuration file, the dalao will automatically restart and output prompts.
Commands
$ dalao-proxy --help
Usage: dalao-proxy [options] [command]
Options:
-V, --version output the version number
-h, --help output usage information
Commands:
start [options] auto detect config & start proxy server
init [options] create an init config file in current folder
mock [options] <method> create a mock file in json format
clean [options] clean cache files
add-plugin [options] <pluginName> add plugin globallyStart Cache Request Response
- Set option
cachetotrue Set appropriate value for
cacheContentType,cacheMaxAge,responseFilteroptionsWhen those three fields satisfied certain conditions, request response would be cached in folder (
cacheDirnameyou specified).
Example:
Here is an simple example of server response data
// send request
POST /api/list HTTP/1.1
...
// get response
connection: keep-alive
content-encoding: gzip
content-type: application/json; charset=UTF-8
date: Fri, 19 Apr 2019 08:35:42 GMT
server: nginx/1.10.3 (Ubuntu)
transfer-encoding: chunked
vary: Accept-Encoding
// response data
{
"status": 1,
"data": {
"list": [
{ "id": 1, "name": "dalao" },
{ "id": 2, "name": "proxy" }
],
"total": 2
}
}The config should be like this:
"cache": true,
"cacheContentType": ["application/json"],
"responseFilter": ["status", 1],Never Read Cache Mode
If you just want to cache response only and get a real proxy response
Recommended when you have completed frontend and backend API docking or requiring high accuracy of response data.
When the backend service crashes during development, you can switch to Read Cache mode to create a fake backend service.
Set option cacheMaxAge to Never Read Cache mode
"cacheMaxAge": ["s", 0]Read Cache Mode
When you're ready to develop front-end pages or need request mock
dalao-proxywould try to look up cache/mock file first, then return a real response after the failure.Recommended: The easier way is to delete
CACHE_TIMEfield in the cached JSON files rather than frequent restarts of the service because of modifying config file.(Updated at v0.8.3)
Set option cacheMaxAge to Read Cache mode. See option cacheMaxAge
// set permanent request cache
"cacheMaxAge": ["s", "*"]
"cacheMaxAge": ["second", "*"]
// set certain expire time request cache (5 min)
"cacheMaxAge": ["m", 5]
"cacheMaxAge": ["minute", 5]Start Request Mock
Updated at v0.9.0 Now,
dalao-proxysupport Javascript-style cache file, so you can import any dependencies to mock your data. For example usingMock.js
Type dalao-proxy mock <HTTP method> and the HTTP method you want to mock
# dalao-proxy mock [options] <method>
$ dalao-proxy mock post
> Request url: /api/list
Mock file created in /home/$(USER)/$(CWD)/.dalao-cache/GET_api_get.json
$ dalao-proxy mock post --js
> Request url: /api/list
Mock file created in /home/$(USER)/$(CWD)/.dalao-cache/GET_api_get.jsPut some mock data into GET_api_get.json file or do whatever you want in js file, then you can access /api/list to get your mock data.
{
"data": {
"list": ["mock", "data"]
},
"code": 200
}const mockjs = require('mockjs');
const list = Mock.mock({
'list|1-10': [{
'id|+1': 1
}]
});
module.exports = {
data: list,
code: 200
};Docs
Configuration file
Dalao will look up the config file in the current working directory while starting up.
Default config filename is dalao.config.json
{
// config file name
"configFileName": "dalao.config.json",
// cache file store
"cacheDirname": ".dalao-cache",
// enable reload when config file changes
"watch": true,
// proxy server host
"host": "localhost",
// proxy server port
"port": 8000,
// proxy target (base setting)
"target": "target.example.com",
// enable proxy request cache (base setting)
"cache": false,
// define response type to cache (base setting)
"cacheContentType": [
"application/json"
],
// define cache valid max time before expired
"cacheMaxAge": [
"second",
0
],
// define response body filter
"responseFilter": [],
// enable logger
"logger": false,
// show debug message
"debug": false,
// custom response headers
"headers": {},
// proxy rule table
"proxyTable": {
// proxy match rule
"/": {
"path": "/"
}
},
// extra plugins
"plugins": []
}Option host
- type: string
default:
localhostWhen configured as
0.0.0.0, other devices on the LAN can also access the service, and the local machine can access usinglocalhost.
Option watch
- type: boolean
- default:
true
Enable proxy server auto reload when config file changes
Option headers
- type: Object
Adding custom request headers or response headers (Updated at v0.9.11).
Example:
{
"headers": {
"request": {
"Token": "THIS-IS-YOUR-FAKE-TOKEN"
},
"response": {
"Authorization": "THIS-IS-YOUR-FAKE-AUTHORIZATION"
}
}
}or only setting response headers by default (backward compatible).
{
"headers": {
"Authorization": "THIS-IS-YOUR-FAKE-AUTHORIZATION"
}
}Option cache
- type: boolean
default:
trueEnable request cache when response satisfies certain conditions.
When a request has been cached, extra field
X-Cache-Requestwill be added into response headers.
Option cacheContentType
- precondition: when
cacheoption istrue - type: Array
default:
['application/json']Cache filtering by response content type with at least one item matches. Support
RegExpexpression
Option cacheMaxAge
- precondition: when
cacheoption istrue - type: Array
- cacheMaxAge0: cache expire time unit
- cacheMaxAge1: cache expire time digit
- when digit comes to
0,dalao-proxywill never try to look up cache file (but still cache request-response) regardless of expire time. - when digit comes to special value
'*', which means cache file will never expire, anddalao-proxywill first try to read and return the cache file, and if it is not found, it would return the real request-response.
- when digit comes to
default:
['second', 0]Cache filtering by cache file expires time.
Support quick restart and take effect immediately.
X-Cache-Expire-TimeandX-Cache-Rest-Timefields will be included in response headers.
Option responseFilter
- precondition: when
cacheoption istrue - type: Array
- default:
['code', 200]
Cache filtering by response body data. Not HTTP status code
Option plugins
type: Array
A list of plugin npm package name.
You will need to add plugins to expand the expandability of
dalao-proxy. See Plugins.
Option proxyTable
- type: Object
default:
{ "/": { "path": "/" } }Proxy route map set.
Proxy route config
{
// proxy target path
// default: `/`
path
// proxy target
// extend base config option `target`
target,
// proxy target path rewrite
pathRewrite,
// route custom config
// default: extend base config
cache,
cacheContentType,
cacheMaxAge,
responseFilter,
}Route option pathRewrite
Use RegExp expression to match target path, and replace with rewrite value.
Example:
"pathRewrite": {
"^/api": ""
}"/api/user/list" will be replaced to be "/user/list"
Plugin SystemBeta
Dalao-proxy support custom plugins now by using option plugins.
Note: Reinstalling
dalao-proxywill cause globally installed plugins to fail (local installation is not affected) and you will need to reinstall the required plugins globally.
Install Plugin
Global Install Plugin
# Globally install
$ dalao-proxy add-plugin <plugin name>
# Globally uninstall
$ dalao-proxy add-plugin -d <plugin name>Local Install Plugin
$ npm install -D dalao-proxy
$ npm install -D <plugin name>Generate config json file
$ npx dalao-proxy initAdd plugin in config json file
{
"plugins": [
"<plugin name>"
]
}Then in package.json
{
"scripts": {
"proxy": "dalao-proxy start"
}
}You can develop your plugins to expand the ability of dalao-proxy.
Available Plugins
Build in(https://github.com/CalvinVon/dalao-proxy/tree/master/src/plugin/check-version)
The dalao-proxy will automaticly check the latest version.
Build in(https://github.com/CalvinVon/dalao-proxy/tree/master/src/plugin/proxy-cache)
Doing awesome request cache and mock work.
@calvin_von/proxy-plugin-monitor A dalao-proxy plugin for request monitoring.
Look at where the dalao-proxy forwarded the request.
- New(https://github.com/CalvinVon/dalao-proxy/tree/master/packages/%40calvin_von/proxy-plugin-redirect) A dalao-proxy plugin for request redirect.
Awesome plugin for debugging the online program locally.
Lifecycle Hook
Dalao-proxy provides bellowing lifecycle hooks among different proxy periods.
Note: All
contextparameters given are not read-only, you can modify and override the values at will.Best Practices: Each plugin produces its own context data under the
contextparameter, and appropriately modifies the behavior ofdalao-proxyand its plugins according to the order in which the plugins are executed.
beforeCreateYou can do some initial operations here.
- type:
Function- params
context
context.config: parsed config object.- detail:
Invoked before proxy server created.onRequest
- type:
Function params
contextcontext.config: parsed config object.context.request: request received by the proxy server. Instance ofhttp.IncomingMessagecontext.response: response that proxy sever need to return. Instance ofhttp.ServerResponse
next- type:
Function params:
error/interruptMessage- If anerrorparam passed in, the request would be interrupted because of throwing an error. - If astringparam passed in, it would be seen as aPluginInterruptwithout throwing an error.A
nextfunction must be called to enter the next period.
- type:
detail:
Invoked when a request received.
onRouteMatch
- type:
Function params
contextcontext.config: parsed config objectcontext.request: request received by the proxy servercontext.response: response that proxy sever need to returncontext.matchedpath: matched path according to request URL.route: matched route object.notFound: whether the route is found.
next- type:
Function params:
error/interruptMessage- If anerrorparam passed in, the request would be interrupted because of throwing an error. - If astringparam passed in, it would be seen as aPluginInterruptwithout throwing an error.A
nextfunction must be called to enter the next period.
- type:
detail:
Invoked when a request URL matches given
proxyTablerules.
beforeProxy
- type:
Function params
contextcontext.config: parsed config objectcontext.request: request received by the proxy servercontext.response: response that proxy sever need to returncontext.matchedpath: matched path according to request URL.route: matched route object.
context.proxyuri: the converted URI address.route: matched route object.
next- type:
Function params:
error/interruptMessage- If anerrorparam passed in, the request would be interrupted because of throwing an error. - If astringparam passed in, it would be seen as aPluginInterruptwithout throwing an error.A
nextfunction must be called to enter the next period.
- type:
detail:
Invoked before
dalao-proxystart to send a proxy request.
afterProxy
- type:
Function params
contextcontext.config: parsed config objectcontext.request: request received by the proxy servercontext.response: response that proxy sever need to returncontext.matchedpath: matched path according to request URL.route: matched route object.
context.proxyuri: the converted URI address.croute: matched route object.request: proxy request object. Instance ofrequest.Request. see request/request on Githubresponse: proxy response object. Instance ofrequest.Response.
context.dataerror: proxy request error. instance ofError.requestrawBody: raw data of request bodybody: parsed data of request bodyquery: parsed data of request querytype: content type of request
responserawBody: raw data of response body of proxybody: parsed data of response body of proxytype: content type of response of proxysize: content size of response of proxyencode: content type of response of proxy
next- type:
Function params:
error/interruptMessage- If anerrorparam passed in, the request would be interrupted because of throwing an error. - If astringparam passed in, it would be seen as aPluginInterruptwithout throwing an error.A
nextfunction must be called to enter the next period.
- type:
detail:
Invoked after
dalao-proxyhas sent a proxy request and has resolved all request and response data.
LICENSE
8 months ago
8 months ago
11 months ago
11 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago