mock-service-plugin
Version:
Simulated backend interface service
103 lines (99 loc) • 2.92 kB
JavaScript
import fs from 'fs';
import path from 'path';
import 'url';
// src/parse-mocks-file.ts
function walk(dir) {
let results = [];
const list = fs.readdirSync(dir);
list.forEach((file) => {
file = dir + "/" + file;
const stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
results = results.concat(walk(file));
} else {
results.push(file);
}
});
return results;
}
// src/constant.ts
var CONTENT_TYPES = {
".json": "application/json",
".txt": "text/plain",
".html": "text/html",
".xml": "application/xml",
".csv": "text/csv",
".md": "text/markdown",
".pdf": "application/pdf",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
".css": "text/css",
".js": "application/javascript",
".yaml": "application/x-yaml",
".yml": "application/x-yaml",
".sse": "text/event-stream"
};
// src/parse-mocks-file.ts
var RE = /^\s*\/\*[*\s]*?([^*\r\n]+)[\s\S]*?@url\s+([^\s]+)(?:[\s\S]*?@method\s+([^\s]+))?(?:[\s\S]*?@content-type\s+([^\s]+))?[\s\S]*?\*\//im;
function parseMocksFile(dir) {
const routes = [];
const Detection = /* @__PURE__ */ new Set();
const files = walk(dir);
(files || []).forEach((filepath) => {
let content = fs.readFileSync(filepath, "utf8").trim() || "{}";
const fileExt = path.extname(filepath).toLowerCase();
const fileName = path.basename(filepath, path.extname(filepath));
let restfulTemplateUrl = filepath;
let describe = "No description";
let contentType = CONTENT_TYPES[fileExt] || "application/json";
let method = "GET";
const match = content.match(RE);
if (match) {
describe = match[1].trim();
restfulTemplateUrl = match[2].trim();
if (match[3]) {
method = match[3].trim().toUpperCase() || "GET";
}
if (match[4]) {
contentType = match[4].trim();
}
const contentEndIndex = content.indexOf("*/") + 2;
if (contentEndIndex > 2) {
content = content.substring(contentEndIndex).trim();
}
}
if (!restfulTemplateUrl.startsWith("/")) {
restfulTemplateUrl = "/" + restfulTemplateUrl;
}
const [routePath, query] = restfulTemplateUrl.split("?");
const routeKey = `${method}:${routePath}`;
if (Detection.has(routeKey)) {
console.warn(
`[Mock Warn]: [${filepath}: ${routeKey}] already exists and will be overwritten`
);
} else {
Detection.add(routeKey);
const params = {
filepath,
fileName,
fileExt,
routeKey,
method,
path: routePath,
query,
restfulTemplateUrl,
describe,
contentType,
responseTemplate: content
};
routes.push(params);
}
});
return routes;
}
export { parseMocksFile };
//# sourceMappingURL=parse-mocks-file.js.map
//# sourceMappingURL=parse-mocks-file.js.map