Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
akupiec
GitHub Repository: akupiec/mad-proxy
Path: blob/master/src/middlewares/mockData.js
115 views
1
const crc = require('crc');
2
const path = require('path');
3
const config = require('../config/config');
4
const utils = require('./utils/utils');
5
6
function queryToString(obj) {
7
return Object.keys(obj).map(key => `${key}=${obj[key]}`).join('&');
8
}
9
10
function parseDirName(config, contextPath, method) {
11
return path.join(config.mock, contextPath.replace(/^\//g, '').replace(/\//g, '_'), method.toUpperCase());
12
}
13
14
let parseFileName = function (contextPath, url) {
15
return url.replace(contextPath, '').replace(/\?.*/, '').replace(/^\//g, '').replace(/\//g, '_');
16
};
17
18
module.exports = function () {
19
return function mockData(req, res, next) {
20
const reqBody = req.body ? req.body.toString() : '' ;
21
const strQuery = queryToString(req.query);
22
const hash = '#' + crc.crc32(strQuery + reqBody).toString(16);
23
const dirName = parseDirName(config, req.baseUrl, req.method);
24
const fileName = parseFileName(req.baseUrl, req.originalUrl);
25
let filePath = path.join(process.cwd(), dirName, fileName) + hash;
26
req.mock = {
27
_hash: hash,
28
_fileName: fileName,
29
filePath,
30
};
31
32
filePath = utils.cacheFileResolve(req.mock.filePath);
33
if (filePath) {
34
req.mock.filePath = filePath;
35
}
36
req.mock.mockExists = !!filePath;
37
38
next();
39
};
40
};
41
42
module.exports.queryToString = queryToString;
43
44