We sometimes make small changes after a project is completed, such as copy changes, fixbugs, minor feature changes. In order to do this, we generally need three steps:
- Logging in to the System with an Account
- The corresponding function page is displayed
- View the returned data structure
Look for the problem account very time, found, do not necessarily have this authority. There are differences between the different accounts, can data structure, sometimes more, development environment suddenly clear library, found no data, so it is hard to get what we want the development environment of instability analysis of the causes of the data (data often lost), not a lot of account (account normally some functionality is hurt each other). All we want is the data structure returned from the back end, so we just have to give a complete data structure for each API interface. The file name is currently generated according to the URL of the API. This ensures that the generated data is unique. Next time the mock visits the same rules, it can be extracted directly
const fs = require('fs-extra');
const path = require('path');
const zlib = require('zlib');
/** * if the file exists, create a new */
function getFilePath(url) {
const filename = url.split('/').filter(str= > str).join('_');
return path.join(__dirname, '.. /mock/', filename + '.json');
}
async function generateMockDataByUrl(url, data) {
const filePath = getFilePath(url);
const exists = await fs.pathExists(filePath);
try {
if(! exists) {await fs.outputJsonSync(filePath, JSON.parse(data), {
spaces: 2}); }}catch (error) {
console.log(data); }}async function getDataFromMockByUrl(url) {
const filePath = getFilePath(url);
const exists = await fs.pathExists(filePath);
if (exists) {
return fs.readJson(filePath);
}
return JSON.stringify([]);
}
function unZip(data) {
return new Promise((resolve, reject) = > {
zlib.gunzip(data, function (err, buffer) {
if (err) {
reject(err);
}
resolve(buffer.toString());
});
});
}
/ / set the headers
function setHeaders(originHeaders, targetHeaders) {
Object.keys(originHeaders).forEach(key= > {
targetHeaders.setHeader(key, originHeaders[key]);
});
}
module.exports = function(app) {
app.use(
['/idgate'.'/login'],
createProxyMiddleware({
changeOrigin: true.target: ' '
selfHandleResponse: true.async onProxyReq(proxyReq, req, res) {
proxyReq.setHeader('host', req.headers.host);
// Enable the mock scheme
if(isMock) { setHeaders( { ... req.headers,'content-type': 'application/json; charset=UTF-8'
}, res);
const data = await getDataFromMockByUrl(req.url);
returnres.send(data); }},async onProxyRes(proxyRes, req, res) {
if(! isMock) { setHeaders(proxyRes.headers, res); }let body = [];
proxyRes.on('data'.function (chunk) {
body.push(chunk);
});
proxyRes.on('end'.async function () {
body = Buffer.concat(body);
// We need to determine the header content-encoding for further processing
if (proxyRes.headers['content-encoding'= = ='gzip') {
const data = await unZip(body);
await generateMockDataByUrl(req.url, data);
} else {
// This solution requires multiple encoding formats to be used with the backend. Gzip defate....
awaitgenerateMockDataByUrl(req.url, body.toString()); } res.end(body); }); }})); };Copy the code
Conclusion All the data are completely true. We can modify the corresponding fields locally for the differences caused by account numbers, which can basically solve the embarrassment of looking for account numbers. Finally, we welcome to discuss a better plan ~.