0.0.2 • Published 5 years ago
proxy-dynamic-middleware v0.0.2
proxy-dynamic-middleware
It's based on http-proxy-middleware, it help you make you mock config file take effects dynamically.
Usage
const express = require('express');
const mockMiddleWare = require('proxy-dynamic-middleware');
const config = require('../config');
// dynamic require
function requireNoCache(modulePath) {
delete require.cache[require.resolve(modulePath)];
return require(modulePath);
}
app.use(mockMiddleWare(() => requireNoCache(config.dev.dynamicConfigPath).mock), {
// supply an hook to handle response
onProxyRes: (proxyRes, _req, _res) => {},
// supply an hook to handle request
onProxyReq: (proxyReq, _req, _res) => {},
});
If you use webpack-dev-server, you can add after option like this:
// these devServer options should be customized in /config/index.js
devServer: {
...
after (app) { // do not use the proxy option
app.use(mockMiddleWare(() => requireNoCache(config.dev.dynamicConfigPath).mock));
},
...
}
options
MockData options:
{
open: false, // false not use mock, true use mock. default false.
changeOrigin: true, // Proxy rule in rules, set changeOrigin dafault value if not defined or if value is a string. default true
rules: {
/**
* '/API_ROOT' we call outer rule, '*' and '/some/route/to/' we call inner rule
* If no outer rule match the request.path, then middleware will go next(), nothing happens
* If outer rule match, but no inner rule match the request.path, proxy to the fallback(default to 'default') url
* You should know that, the outer root '/API_ROOT' will be ignore if matched when proxys.
* Example:
* http://localhost:8080/API_ROOT/some/route/to/here -> http://172.172.2.89:8000/route/to/here
*/
'/API_ROOT': {
/**
* Who match longest, then take effects!
* Same use like the proxyTable (but changeOrigin be true as default)
* '*' or '/' or '' match everyone, but match length is considered 1.
* You can use keywords for mock origins.
*/
'*': 'mock',
'/some/route/to/': {
target: 'dev',
pathRewrite: {
'^some': '',
},
},
// Has higher priority than /some/route/to/ as it's longer
'/some/route/to/there': 'dev'
},
},
/**
* If you don't set outer rule's fallback, default to 'default'
* If you set outer rule's fallback to dev
* when outer rule '/API_ROOT' match, inner rule not match
* the request will proxy to the 'dev' url
*/
fallback: {
'/API_ROOT': 'dev',
},
/**
* 'default' is a special keyword, you should set a value for it
*/
keywords: {
'default': 'http://dev.yousite.com/',
'mock': 'http://yapi.elephtribe.net/mock/1111/',
'dev': 'http://172.172.2.89:8000',
},
}