@tasolutions/express-core
Version:
All libs for express
59 lines (50 loc) • 2.44 kB
JavaScript
const fs = require("fs");
const path = require("path");
const chokidar = require("chokidar");
// Đường dẫn đến thư mục chứa mã nguồn
const workflowsDirectory = path.join(__dirname, "src");
let workflowsMapping = {}; // Khai báo là biến global
// Hàm để quét workflows
function findWorkflows(dir) {
const files = fs.readdirSync(dir);
files.forEach(file => {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
// Nếu là thư mục, gọi đệ quy
findWorkflows(filePath);
} else if (file.endsWith('.workflow.js')) { // Kiểm tra nếu tệp là *.workflow.js
const workflow = require(filePath); // Import tệp workflow
// Kiểm tra xem workflow có tồn tại không và thêm vào mapping
if (workflow) {
const workflowName = path.basename(file, '.workflow.js'); // Lấy tên tệp mà không có đuôi
// workflowsMapping[workflowName] = workflow; // Lưu trữ đối tượng workflow vào mapping
Object.assign(workflowsMapping, workflow);
} else {
console.log(`No valid workflow found in ${filePath}`);
}
}
});
}
// Hàm để ghi workflowsMapping vào tệp
function writeWorkflowsToFile() {
const indexPath = path.join(__dirname, "workflows/index.js");
fs.writeFileSync(indexPath, `const workflowsMapping = ${JSON.stringify(workflowsMapping, null, 2)};\n\nmodule.exports = workflowsMapping;`, 'utf8');
console.log('Workflows mapping has been updated in workflows/index.js');
}
// Hàm tổng thể để quét workflows và ghi vào tệp
function processWorkflows() {
workflowsMapping = {}; // Reset mapping
findWorkflows(workflowsDirectory); // Quét workflows
writeWorkflowsToFile(); // Ghi vào tệp
}
// Xuất các hàm để sử dụng ngoài
module.exports = { processWorkflows, workflowsDirectory };
// Thiết lập watcher (nếu cần)
const watcher = chokidar.watch(workflowsDirectory, { persistent: true });
watcher.on('change', (filepath) => {
if (filepath.endsWith('.workflow.js')) {
console.log(`${path.basename(filepath)} file changed, updating workflows mapping...`);
processWorkflows(); // Gọi hàm tổng thể để quét lại các workflows khi có thay đổi
}
});