Web page mock middleware.
- Simple url and mock file mapping rules.
- Support
*.js
,*.json
and common datas. - Auto find all scenes and easy change it
Use ?__scene[={scene}]
to select mock scene, default scene is default
.
{url}?__scene={scene} => {datadir}{url}/{scene}.js
$ npm install koa-mock
Using nunjucks template engine for example:
- NOTICE You must implement
ctx.render(ctx, view, data)
generator function first. - Use
__scene[={scene}]
querystring to enable mock and select one mock scene.
const path = require('path');
const nunjucks = require('nunjucks');
const Koa = require('koa');
const mock = require('koa-mock');
const app = new Koa();
app.use(mock({
datadir: path.join(__dirname, 'mocks')
}));
nunjucks.configure(path.join(__dirname, 'views'));
app.context.render = async function(ctx, view, data) {
ctx.body = nunjucks.render(view, data);
};
app.listen(1984);
- /mocks
- default.js =>
{name: 'fengmk2', __view: 'home.html'}
- /users
- /1
- default.js =>
{name: 'default-user', __view: 'profile.html'}
- fengmk2.js =>
{name: 'fengmk2', __view: 'profile.html'}
- default.js =>
- /1
- default.js =>
- /views
- home.html =>
<p>welcome home, {{name}}</p>
- profile.html =>
<p>profile, {{name}}</p>
- home.html =>
$ curl http://localhost:1984/?__scene
Status: 200
<p>welcome home, fengmk2</p>
$ curl http://localhost:1984/users/1?__scene=default
Status: 200
<p>profile, default-user</p>
$ curl http://localhost:1984/users/1?__scene=fengmk2
Status: 200
<p>profile, fengmk2</p>
$ curl http://localhost:1984/
Status: 404
Not Found
MIT