'use strict'; /** * 外部打单平台服务注册入口。 * * 约定:一个平台一个文件,文件名 = 平台标识(external_print_platforms.code), * 例如 code 为 dgj 的平台对应本目录下的 dgj.js;文件内的类声明 static code = 'dgj', * 必须与表里的 code 完全一致。以 `_` 开头的文件不参与注册(草稿/临时文件)。 */ const fs = require('fs'); const path = require('path'); const PrintPlatformService = require('./base'); /** 平台实现目录 */ const SERVICE_DIR = __dirname; /** * 是否作为平台实现加载:`_` 开头的为模板/草稿,base.js 与 index.js 为基础设施 * @param {string} file 文件名 * @return {boolean} 是否加载 */ function isServiceFile(file) { return file.endsWith('.js') && !file.startsWith('_') && file !== 'base.js' && file !== 'index.js'; } /** code -> 平台服务类,首次使用时扫描目录建立索引 */ let registry = null; /** * 扫描目录加载全部平台实现,按 static code 建立索引 * @return {Map} 平台标识 -> 服务类 */ function loadRegistry() { if (registry) return registry; const map = new Map(); for (const file of fs.readdirSync(SERVICE_DIR).filter(isServiceFile)) { const Service = require(path.join(SERVICE_DIR, file)); const code = Service && Service.code; if (!code) throw new Error(`外部打单平台服务 ${file} 缺少 static code`); if (map.has(code)) throw new Error(`外部打单平台服务 code 重复:${code}(${file})`); map.set(code, Service); } registry = map; return registry; } /** * 按平台标识取服务类 * @param {string} code 平台标识(external_print_platforms.code) * @return {Function|null} 服务类,未实现时返回 null */ function getPrintPlatformServiceClass(code) { return loadRegistry().get(String(code)) || null; } /** * 平台是否已有服务实现 * @param {string} code 平台标识(external_print_platforms.code) * @return {boolean} 是否已实现 */ function hasPrintPlatformService(code) { return !!getPrintPlatformServiceClass(code); } /** * 创建平台服务实例 * @param {string} code 平台标识(external_print_platforms.code) * @param {Object} options 构造参数:{ platform, account } * @return {PrintPlatformService} 平台服务实例 */ function createPrintPlatformService(code, options = {}) { const Service = getPrintPlatformServiceClass(code); if (!Service) { throw new Error(`外部打单平台 ${code} 暂无服务实现,请先在 app/lib/printPlatform 下新增对应 service 类`); } return new Service(options); } /** * 已实现服务的平台标识列表 * @return {string[]} 平台标识列表 */ function listPrintPlatformServiceCodes() { return Array.from(loadRegistry().keys()); } module.exports = { PrintPlatformService, getPrintPlatformServiceClass, hasPrintPlatformService, createPrintPlatformService, listPrintPlatformServiceCodes, };