Mocor 是目前为止最方便的快速配置生成服务端API接口的 Node.js 库。
- 非常易于使用
- 自动生成API文档
- 结合AirCode使用效果更佳
- 本地结合Koa使用:
const Koa = require('koa');
const {bodyParser} = require("@koa/bodyparser");
const {Mock} = require('mocor');
const app = new Koa();
const mock = new Mock();
mock.use({
hello: 'mocor',
}, {
allowMethods: ['GET','POST']
});
app
.use(bodyParser())
.use(async (ctx) => {
const params = ctx.method === 'GET' ? ctx.query : ctx.request.body;
const result = await mock.execute(params, ctx);
if(ctx.response.headers['content-type'] === 'application/json') {
ctx.body = JSON.stringify(result);
} else {
ctx.body = result;
}
});
app.listen(3000);
访问 http://localhost:3000
能看到API页面:
- 直接使用 AirCode(推荐)
// @see https://docs.aircode.io/guide/functions/
const aircode = require('aircode');
const {Mock} = require('mocor');
const mock = new Mock('hello', 'This is a demo api generated by mocor.');
mock.post({
message: 'Hi, Mocor',
});
module.exports = mock.compile();
Mocor 提供了功能强大的 API 生成辅助函数来生成各种数据,以下是 Mocor 内置的辅助函数:
- randomFloat(from = 0, to = 1)
- 生成一个范围内的随机浮点数
- randomInteger(from = 0, to = 1000)
- 生成一个范围内的随机整数
- randomString(len = 16)
- 生成一个指定长度的随机字符串
- randomUUID()
- 生成一个UUID字符串
- randomDate(from = new Date(0), to = new Date())
- 生成一个指定时间范围的随机日期
- repeat(schema, min = 3, max = min)
- 重复指定次数,生成列表
- join(list, joint = '')
- 将列表连接成字符串
下面这个例子生成5到10条学生信息,包括学生的名字、ID以及成绩。
// @see https://docs.aircode.io/guide/functions/
const aircode = require('aircode');
const {Mock, repeat, randomInteger, randomUUID} = require('mocor');
const mock = new Mock('random list', 'This is a demo api generated by mocor.');
const genName = () => {
let i = 0;
return () => `student${i++}`;
}
mock.use(repeat({
name: genName(),
score: randomInteger(0, 101),
id: randomUUID(),
}, 5, 10), {
allowMethods: ['GET', 'POST'],
});
module.exports = mock.compile();
- randomLatinLetter()
- 生成一个拉丁文(英文)字母
- randomLatinWord(minLetters = 3, maxLatters = 12)
- 生成一个字母数量范围内的单词
- randomLatinParagraph(minWords = 10, maxWords = 40)
- 生成一个由一定单词数量组成的段落
- randomLatinArticle(minParagraph = 3, maxParagraph = 10)
- 生成一篇一定段落数量的文章
- randomChineseName()
- 生成一个随机中文名
- randomChineseParagraph()
- 生成一个随机的中文段落
- randomChineseArticle(min = 200, max = 800)
- 生成一定字数的随机中文文章
下面这个例子生成中文的学生信息:
// @see https://docs.aircode.io/guide/functions/
const aircode = require('aircode');
const {Mock, repeat, randomInteger, randomUUID, randomChineseName, randomChineseArticle} = require('mocor');
const mock = new Mock('chinese students', 'This is a demo api generated by mocor.');
mock.use(repeat({
name: randomChineseName(),
scores: repeat(randomInteger(50, 101), 5),
id: randomUUID(),
comment: randomChineseArticle(),
}, 5, 10), {
allowMethods: ['GET', 'POST'],
});
module.exports = mock.compile();
- param(name, type = 'any', defaultValue = null, info = ' ')
- 使用传入的参数来生成数据
- randomPick(...list)
- 从数组中等概率地获得随机值
- randomPickWeight(...list)
- 根据每一条数据中的权重来随机获取值
- poll(...list)
- 轮询数组中的值
下面这个例子根据不同的参数来返回不同的数据:
// @see https://docs.aircode.io/guide/functions/
const aircode = require('aircode');
const {Mock, param} = require('mocor');
const mock = new Mock('params', 'This is a demo api generated by mocor.');
mock.post((args) => {
const type = param('type', 'string', 'odd', 'get numbers even or odd')(args);
if(type === 'odd') return [1, 3, 5, 7, 9];
return [0, 2, 4, 6, 8];
});
module.exports = mock.compile();
下面这个例子模拟32条分页数据,根据 page
的值返回不同的数据条目:
// @see https://docs.aircode.io/guide/functions/
const aircode = require('aircode');
const {Mock, param, repeat, randomChineseName, randomInteger} = require('mocor');
const mock = new Mock('params', 'This is a demo api generated by mocor.');
mock.post((args) => {
const total = 32;
const pn = param('pn', 'number', 1, 'the page number')(args);
const n = Math.min(10, Math.max(0, total - (pn - 1) * 10));
return repeat({
name: randomChineseName(),
score: randomInteger(),
}, n);
});
module.exports = mock.compile();
下面这个例子模拟一定概率下报错:
// @see https://docs.aircode.io/guide/functions/
const aircode = require('aircode');
const {Mock, repeat, randomChineseName, randomInteger} = require('mocor');
const mock = new Mock('Random error', 'This is a demo api generated by mocor.');
mock.post(({context}) => {
if(Math.random() > 0.5) {
context.status(500);
return {
error: 'fatal error',
}
}
return repeat({
name: randomChineseName(),
score: randomInteger(),
}, 5);
});
module.exports = mock.compile();
如果你要先用模拟数据调试,随时切换到正式环境,那么在 AirCode 中,你可以这么做:
首先创建模拟环境云函数 student-mock.js
// @see https://docs.aircode.io/guide/functions/
const aircode = require('aircode');
const {Mock, repeat, randomInteger, randomUUID, randomChineseName, randomChineseArticle} = require('mocor');
const mock = new Mock('chinese students', 'This is a demo api generated by mocor.');
mock.use(repeat({
name: randomChineseName(),
scores: repeat(randomInteger(50, 101), 5),
id: randomUUID(),
comment: randomChineseArticle(),
}, 5, 10), {
allowMethods: ['GET', 'POST'],
});
module.exports = mock.compile();
然后用如下代码创建正式环境的 student.js
// @see https://docs.aircode.io/guide/functions/
const aircode = require('aircode');
const {mocking} = require('mocor');
module.exports = mocking(require('./student-mock.js'),
async function (params, context) {
console.log('Received params:', params);
return {
message: 'Hi, AirCode.',
};
});
这样我们访问正式的 API 就可以通过设置 HTTP 请求头 x-motor
值为 1 来使用模拟数据,不设置这个请求头则返回真实数据。
而 API 文档仍然可以通过模拟数据的云函数进行访问。