const express = require("express"); const http = require("http"); const cors = require("cors"); const bodyParser = require("body-parser"); const { loadEnv, getConfig } = require("./src/core/config"); const { success, fail } = require("./src/core/result"); const { handleQuery, queryStandardResource } = require("./src/core/query-controller"); const { handleSync } = require("./src/sync/sync-controller"); const { connectMongo, ensureIndexes, isMongoAvailable, getMongoDisabledReason } = require("./src/mongo"); const { handleYktCustomerHisSync } = require("./src/ykt/customer-his-sync"); const { attachGateway, listEdges } = require("./src/gateway/edge-registry"); const { queryGatewayResource, queryGatewayCustomerHisSync } = require("./src/gateway/router"); const { startEdgeClient } = require("./src/edge/client"); loadEnv(); const app = express(); const config = getConfig(); const server = http.createServer(app); app.set("trust proxy", true); app.use(cors()); app.use(bodyParser.json({ limit: "8mb" })); app.use(bodyParser.urlencoded({ extended: true, limit: "8mb" })); app.use(bodyParser.text({ type: ["text/*", "application/xml", "*/xml", "application/soap+xml"], limit: "8mb" })); app.get("/healthz", (req, res) => { res.json( success({ data: { service: "hospital-adapter-service", status: "ok", role: config.role, mongo: isMongoAvailable() ? "connected" : "disabled", mongoMessage: isMongoAvailable() ? "" : getMongoDisabledReason(), edges: config.role === "gateway" ? listEdges() : undefined, }, }) ); }); app.post("/api/ykt/customerHisSync", async (req, res) => { const queryResource = config.role === "gateway" ? queryGatewayResource : ({ hospitalCode, resource, query }) => queryStandardResource({ hospitalCode, resource, query, saveSnapshot: false }).then((result) => ({ status: "success", message: "查询成功", ...result })); return handleYktCustomerHisSync(req, res, { queryResource, forwardCustomHisSync: config.role === "gateway" ? queryGatewayCustomerHisSync : undefined, }); }); app.post("/api/his/query", handleQuery); app.post("/api/:hospitalCode/:resource/query", handleQuery); app.post("/api/his/sync", handleSync); app.use((req, res) => { res.status(404).json(fail("接口不存在", "NOT_FOUND")); }); async function start() { await connectMongo(); await ensureIndexes(); if (config.role === "gateway") attachGateway(server); server.listen(config.port, "0.0.0.0", () => { console.log(`[hospital-adapter-service] ${config.role} listening on :${config.port}`); if (config.role === "edge") startEdgeClient(); }); } start().catch((err) => { console.error("[hospital-adapter-service] start failed", err); process.exit(1); });