123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- const path = require("path");
- const fs = require("fs");
- /**
- * 读取本地mock数据
- * @param {*} req
- */
- function readMockData(req) {
- const { url, pathname, param, method } = req;
- return new Promise((resolve, reject) => {
- const filepath = path.resolve(__dirname, "./" + pathname + ".js");
- const fileExist = fs.existsSync(filepath);
- if (!fileExist) {
- const msg = `'${url}': mock data is not exist!`;
- reject({
- statusCode: 404,
- body: null,
- message: msg,
- });
- } else {
- try {
- delete require.cache[require.resolve(filepath)];
- const response = require(filepath);
- if (typeof response === "function") {
- const responseFun = response(req);
- resolve(responseFun);
- return;
- }
- resolve(response);
- } catch (err) {
- console.log("readMockError:", err);
- const msg = `'${url}': parse mock file error!`;
- reject({
- statusCode: 500,
- body: null,
- message: msg,
- });
- }
- }
- });
- }
- /**
- * express中间件,实现ajax mock数据功能
- * @param {*} app
- */
- module.exports = function mock(app) {
- app.all("*", function (req, res, next) {
- const method = req.method.toLocaleUpperCase();
- const param = method === "GET" ? req.query : req.body;
- // 请求日志打印
- console.log(req.method, req.url, param, Date.now());
- // 只处理ajax请求
- if (
- req.headers["x-requested-with"] === "XMLHttpRequest" ||
- req.path.indexOf("/api-mock") > -1
- ) {
- readMockData({
- url: req.url,
- pathname: req.path,
- param,
- method,
- })
- .then((response) => {
- res.status(response.statusCode || 200);
- res.setHeader("Content-Type", "application/json");
- res.end(JSON.stringify(response.body));
- })
- .catch((err) => {
- res.status(err.statusCode || 404);
- res.end();
- });
- } else {
- next();
- }
- });
- };
|