UNPKG

@tasolutions/express-core

Version:
59 lines (50 loc) 2.48 kB
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 interfacesDirectory = path.join(__dirname, "src"); let interfacesMapping = {}; // Khai báo là biến global // Hàm để quét interfaces function findInterfaces(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 findInterfaces(filePath); } else if (file.endsWith('.interface.js')) { // Kiểm tra nếu tệp là *.interface.js const interface = require(filePath); // Import tệp interface // Kiểm tra xem interface có tồn tại không và thêm vào mapping if (interface) { const interfaceName = path.basename(file, '.interface.js'); // Lấy tên tệp mà không có đuôi // interfacesMapping[interfaceName] = interface; // Lưu trữ đối tượng interface vào mapping Object.assign(interfacesMapping, interface); } else { console.log(`No valid interface found in ${filePath}`); } } }); } // Hàm để ghi interfacesMapping vào tệp function writeInterfacesToFile() { const indexPath = path.join(__dirname, "interfaces/index.js"); fs.writeFileSync(indexPath, `const interfacesMapping = ${JSON.stringify(interfacesMapping, null, 2)};\n\nmodule.exports = interfacesMapping;`, 'utf8'); console.log('Interfaces mapping has been updated in interfaces/index.js'); } // Hàm tổng thể để quét interfaces và ghi vào tệp function processInterfaces() { interfacesMapping = {}; // Reset mapping findInterfaces(interfacesDirectory); // Quét interfaces writeInterfacesToFile(); // Ghi vào tệp } // Xuất các hàm để sử dụng ngoài module.exports = { processInterfaces, interfacesDirectory }; // Thiết lập watcher (nếu cần) const watcher = chokidar.watch(interfacesDirectory, { persistent: true }); watcher.on('change', (filepath) => { if (filepath.endsWith('.interface.js')) { console.log(`${path.basename(filepath)} file changed, updating interfaces mapping...`); processInterfaces(); // Gọi hàm tổng thể để quét lại các interfaces khi có thay đổi } });