git repo github.com/quanxiaoxia…javascript
在我目前工做環境下,服務端給個接口,我再根據接口所須要傳入的參數和返回的數據格式,來調整前端業務邏輯,有時候碰到服務端跑不起來,手頭上的工做就無法再繼續了,因此我要有個mock server,首先想到的是json-server,可是咱們服務端接口並非標準的REST API,並且生成本身想要的數據仍是太麻煩,也找不到別的更好的工具了,因此本身動手就寫個吧。html
個人思路是這樣的,啓動一個服務,而後會讀取相關的配置文件,可以根據配置文件上的url,可以有這些處理:前端
有了需求後,接下來就是實現了
啓動項目的時候總有個命令名吧,那就叫norice好了,因此配置文件叫norice.config.jsjava
module.exports = {
paths: {
'/aaa': './data/.json',
},
};複製代碼
module.exports = {
paths: {
'/aaa': 'http://proxy-path.com',
},
};複製代碼
能夠對特定的路徑作出相應的代理,並可以自定義headerwebpack
module.exports = {
paths: {
'/aaa/*': {
options: {
pathRewrite: {
'^/aaa': '',
},
headers: {
Cookie: 'JSESSIONID=2342342DE234234',
},
},
success: 'http://propx-path.com',
},
},
};複製代碼
這樣能夠把http://localhost:3000/aaa/111/222,代理到http://proxy-path.com/111/222git
const mock = require('mock');
const faker = require('faker');
const _ = require('lodash');
module.exports = {
paths: {
'/faker': ({ json }) => json(_.times(faker.random.number({ min:10, max: 20 }), i => ({
index: i,
name: faker.name.findName(),
}))),
'/mockjs': ({ json }) => json(mock.mock({
'list|1-10': [{
'id|+1': 1,
}],
})),
},
};複製代碼
module.exports = {
paths: {
'/aaa': {
status: 400,
success: {
msg: 'params error',
},
},
},
};複製代碼
module.exports = {
paths: {
'/aaa': ({ json, file, proxy, req }) => {
const { name } = req.query;
if (name === 'aaa') {
json({ name: 'aaa' });
} else if (name === 'bbb') {
const convertor = d => ({ ...d, age: 11 });
file('./data/file.json', convertor);
} else if (name === 'ccc') {
const convertor = d => ({ ...d, age: 22 });
proxy('http://proxy-path.com/some/path', convertor);
} else {
throw new Error('no handle');
}
},
},
};複製代碼
module.exports = {
paths: {
'/aaa': {
validate: {
name: Proptypes.oneOf(['quan', 'rice', 'foo']).isRequired,
age: Proptypes.number,
phone: Proptypes.match(/^1\d{10}$/),
birthday: Proptypes.date('YYYY-MM-DD'), // 格式參考 http://momentjs.com/docs/#/parsing/string-format/
address: Proptypes.isRequired,
},
success: { msg: 'success' },
error: { msg: 'invalidate' },
},
},
};複製代碼
module.exports = {
webpack: './webpack.config.development.js', // webpack配置參考 https://github.com/glenjamin/webpack-hot-middleware 和 https://github.com/webpack/webpack-dev-middleware
paths: {},
};複製代碼
const express = require('express');
const compression = rquire('compression');
module.exports = {
middlewares: [
compression(),
express.static(path.resolve(__dirname, 'dist')),
],
paths: {
'/': './dist/index.html',
'/quan': './dist/index.html',
'/rice': {
success: {
name: 'rice',
},
},
},
};複製代碼