feat(hospital): 新增医院基础信息接口与复旦排名
This commit is contained in:
@@ -0,0 +1,174 @@
|
||||
import mongoose from "mongoose";
|
||||
import { DBModel } from "../models/index.js";
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
|
||||
/**
|
||||
* 医院基础信息:维护名称、主体名称、省市、地址、电话、科室、等级。
|
||||
* 分院/院区作为独立医院记录,不设上下级关系;名称约定为「主体名称-分院名称」。
|
||||
*/
|
||||
class HandlerHospital {
|
||||
// 单页最大条数,避免 pageSize 传超大值一次拖库
|
||||
static MAX_PAGE_SIZE = 200;
|
||||
|
||||
// 可写字段白名单(pinyin / pinyinFL 由服务端自动生成,不接受手写)
|
||||
static FIELDS = ["name", "entityName", "province", "city", "address", "phone", "departments", "level"];
|
||||
|
||||
// 解析分页参数并夹紧上限
|
||||
static parsePaging(query = {}) {
|
||||
const page = Math.max(1, parseInt(query.page) || 1);
|
||||
const rawSize = parseInt(query.pageSize) || 20;
|
||||
const pageSize = Math.min(Math.max(1, rawSize), HandlerHospital.MAX_PAGE_SIZE);
|
||||
return { page, pageSize };
|
||||
}
|
||||
|
||||
// 按白名单挑选请求体字段,避免 schema 之外的字段被写入
|
||||
static pickFields(body = {}) {
|
||||
const picked = {};
|
||||
for (const key of Object.keys(body || {})) {
|
||||
if (HandlerHospital.FIELDS.includes(key)) {
|
||||
picked[key] = body[key];
|
||||
}
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并规整字段(只处理请求中出现的字段,未出现的沿用原值)
|
||||
* @param {Object} fields 已按白名单挑出的字段
|
||||
* @param {boolean} requireName 新增时要求名称必填
|
||||
* @returns {string|null} 不合规时返回提示文案
|
||||
*/
|
||||
static validateFields(fields, { requireName = false } = {}) {
|
||||
if (requireName || fields.name !== undefined) {
|
||||
const name = String(fields.name ?? "").trim();
|
||||
if (!name) return "请填写医院名称";
|
||||
fields.name = name;
|
||||
}
|
||||
|
||||
for (const key of ["entityName", "province", "city", "address", "phone", "level"]) {
|
||||
if (fields[key] !== undefined) {
|
||||
fields[key] = String(fields[key] ?? "").trim();
|
||||
}
|
||||
}
|
||||
|
||||
if (fields.departments !== undefined) {
|
||||
if (!Array.isArray(fields.departments)) return "科室需为字符串数组";
|
||||
fields.departments = fields.departments
|
||||
.map((item) => String(item ?? "").trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// 校验失败统一转成 400,避免把 mongoose 字段细节抛给前端
|
||||
static handleWriteError(ctx, err) {
|
||||
if (err?.code === 11000) {
|
||||
return ResponseUtil.badRequest(ctx, "医院名称已存在,请使用「主体名称-分院名称」格式避免重名");
|
||||
}
|
||||
if (err?.name === "ValidationError") {
|
||||
return ResponseUtil.badRequest(ctx, "医院信息不合法,请检查名称、科室等字段");
|
||||
}
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
|
||||
// 医院列表(公开):支持分页、关键词搜索与按主体名称列分院
|
||||
async getHospitals(ctx) {
|
||||
try {
|
||||
const keyword = String(ctx.request.query.keyword || "").trim();
|
||||
const entityName = String(ctx.request.query.entityName || "").trim();
|
||||
const { page, pageSize } = HandlerHospital.parsePaging(ctx.request.query);
|
||||
const result = await DBModel.Hospital.findHospitals({ page, pageSize, keyword, entityName });
|
||||
return ResponseUtil.success(ctx, result, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// 医院详情(公开)
|
||||
async getHospitalById(ctx) {
|
||||
try {
|
||||
const id = ctx.params.id;
|
||||
|
||||
// 非法 ObjectId 会让 mongoose 抛 CastError,先挡掉
|
||||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||||
return ResponseUtil.badRequest(ctx, "医院ID不合法");
|
||||
}
|
||||
|
||||
const hospital = await DBModel.Hospital.findHospitalById(id);
|
||||
if (!hospital) {
|
||||
return ResponseUtil.notFound(ctx, "医院不存在");
|
||||
}
|
||||
|
||||
return ResponseUtil.success(ctx, { hospital }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// 新增医院(管理员)
|
||||
async createHospital(ctx) {
|
||||
try {
|
||||
const fields = HandlerHospital.pickFields(ctx.request.body);
|
||||
const invalid = HandlerHospital.validateFields(fields, { requireName: true });
|
||||
if (invalid) {
|
||||
return ResponseUtil.badRequest(ctx, invalid);
|
||||
}
|
||||
|
||||
const hospital = await DBModel.Hospital.createHospital(fields);
|
||||
return ResponseUtil.success(ctx, { hospital }, "创建成功");
|
||||
} catch (err) {
|
||||
return HandlerHospital.handleWriteError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// 修改医院(管理员)
|
||||
async updateHospital(ctx) {
|
||||
try {
|
||||
const id = ctx.params.id;
|
||||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||||
return ResponseUtil.badRequest(ctx, "医院ID不合法");
|
||||
}
|
||||
|
||||
const fields = HandlerHospital.pickFields(ctx.request.body);
|
||||
if (Object.keys(fields).length === 0) {
|
||||
return ResponseUtil.badRequest(ctx, "没有可更新的字段");
|
||||
}
|
||||
|
||||
const invalid = HandlerHospital.validateFields(fields);
|
||||
if (invalid) {
|
||||
return ResponseUtil.badRequest(ctx, invalid);
|
||||
}
|
||||
|
||||
const hospital = await DBModel.Hospital.updateHospitalById(id, fields);
|
||||
if (!hospital) {
|
||||
return ResponseUtil.notFound(ctx, "医院不存在");
|
||||
}
|
||||
|
||||
return ResponseUtil.success(ctx, { hospital }, "更新成功");
|
||||
} catch (err) {
|
||||
return HandlerHospital.handleWriteError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// 删除医院(管理员)
|
||||
async deleteHospital(ctx) {
|
||||
try {
|
||||
const id = ctx.params.id;
|
||||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||||
return ResponseUtil.badRequest(ctx, "医院ID不合法");
|
||||
}
|
||||
|
||||
const hospital = await DBModel.Hospital.deleteHospitalById(id);
|
||||
if (!hospital) {
|
||||
return ResponseUtil.notFound(ctx, "医院不存在");
|
||||
}
|
||||
|
||||
return ResponseUtil.success(ctx, { hospital }, "删除成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { HandlerHospital };
|
||||
@@ -4,6 +4,7 @@ import mongoose from 'mongoose';
|
||||
import { EscortRecordSchema } from "./schema/escort_record.js"
|
||||
import { HealthProfileSchema } from "./schema/health_profile.js"
|
||||
import { OrganizationSchema } from "./schema/organization.js"
|
||||
import { HospitalSchema } from "./schema/hospital.js"
|
||||
import { EmployeeSchema } from "./schema/employee.js"
|
||||
import { EmployeeReviewSchema } from "./schema/employee_review.js"
|
||||
import { TrainingApplicationSchema } from "./schema/training_application.js"
|
||||
@@ -16,6 +17,7 @@ class MongoDBSchema {
|
||||
this.User = null;
|
||||
this.EscortRecord = null;
|
||||
this.Organization = null;
|
||||
this.Hospital = null;
|
||||
this.Employee = null;
|
||||
this.HealthProfile = null;
|
||||
this.EmployeeReview = null;
|
||||
@@ -48,6 +50,7 @@ class MongoDBSchema {
|
||||
this.EscortRecord = this.dbConnection.model('escort_record', EscortRecordSchema)
|
||||
this.HealthProfile = this.dbConnection.model('health_profile', HealthProfileSchema)
|
||||
this.Organization = this.dbConnection.model('organization', OrganizationSchema)
|
||||
this.Hospital = this.dbConnection.model('hospital', HospitalSchema)
|
||||
this.Employee = this.dbConnection.model('employee', EmployeeSchema)
|
||||
this.EmployeeReview = this.dbConnection.model('employee_review', EmployeeReviewSchema)
|
||||
this.TrainingApplication = this.dbConnection.model('training_application', TrainingApplicationSchema)
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
"use strict";
|
||||
|
||||
import mongoose from "mongoose";
|
||||
import { pinyin } from "pinyin-pro";
|
||||
import { hospitalRanking } from "../../resource/fudan_hospital_ranking.js";
|
||||
|
||||
// 复旦综合榜未上榜医院的默认档位:排在所有上榜医院之后
|
||||
const DEFAULT_FUDAN_RANK = 999;
|
||||
|
||||
// 复旦综合榜只有等级档位(A+++++ / A++++ / A+++),同档不分先后;
|
||||
// 按榜单出现顺序映射成 1/2/3,后续榜单新增更低档位也能自动延续
|
||||
const FUDAN_GRADE_ORDER = new Map();
|
||||
for (const item of hospitalRanking.rankings) {
|
||||
if (!FUDAN_GRADE_ORDER.has(item.grade)) {
|
||||
FUDAN_GRADE_ORDER.set(item.grade, FUDAN_GRADE_ORDER.size + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// 名称归一:统一全角括号、去掉括号别名、空白与连接符,便于跨数据源匹配
|
||||
const normalizeHospitalName = (value) =>
|
||||
String(value || "")
|
||||
.trim()
|
||||
.replace(/(/g, "(")
|
||||
.replace(/)/g, ")")
|
||||
.replace(/[((][^))]*[))]/g, "")
|
||||
.replace(/[\s\--—–·]/g, "");
|
||||
|
||||
const FUDAN_RANK_BY_NAME = new Map();
|
||||
for (const item of hospitalRanking.rankings) {
|
||||
const key = normalizeHospitalName(item.name);
|
||||
if (key && !FUDAN_RANK_BY_NAME.has(key)) {
|
||||
FUDAN_RANK_BY_NAME.set(key, {
|
||||
rank: FUDAN_GRADE_ORDER.get(item.grade) || DEFAULT_FUDAN_RANK,
|
||||
grade: item.grade,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析医院对应的复旦综合榜档位
|
||||
* 以主体名称优先;名称带括号别名时先归一,再处理统一前缀与历史别名。
|
||||
* @param {string[]} names 依次尝试的名称
|
||||
* @returns {{rank:number, grade:string}|null}
|
||||
*/
|
||||
const resolveFudanRank = (names = []) => {
|
||||
for (const value of names) {
|
||||
const key = normalizeHospitalName(value);
|
||||
if (!key) continue;
|
||||
|
||||
const direct = FUDAN_RANK_BY_NAME.get(key);
|
||||
if (direct) return direct;
|
||||
|
||||
// 301 各医学中心/院区统一归到复旦榜的「中国人民解放军总医院(301)」
|
||||
if (key.startsWith("中国人民解放军总医院")) {
|
||||
const hit = FUDAN_RANK_BY_NAME.get("中国人民解放军总医院");
|
||||
if (hit) return hit;
|
||||
}
|
||||
|
||||
// 兼容「首都医科大学附属北京积水潭医院」这类多了统一前缀的名称
|
||||
const withoutPrefix = key.replace(/^首都医科大学附属/, "");
|
||||
if (withoutPrefix !== key) {
|
||||
const hit = FUDAN_RANK_BY_NAME.get(withoutPrefix);
|
||||
if (hit) return hit;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Hospital Schema
|
||||
* 医院基础信息:名称、主体名称、拼音、省市、地址、电话、科室、等级、复旦综合榜档位。
|
||||
* 分院/院区按独立医院记录,不设 parentId;名称约定为「主体名称-分院名称」。
|
||||
*/
|
||||
const HospitalSchema = mongoose.Schema(
|
||||
{
|
||||
name: { type: String, required: true, comment: "医院名称,约定为「主体名称-分院名称」" },
|
||||
entityName: { type: String, default: "", index: true, comment: "主体名称;为空时自动取 name 分隔符前的部分" },
|
||||
pinyin: { type: String, default: "", index: true, comment: "医院名称全拼(小写无分隔)" },
|
||||
pinyinFL: { type: String, default: "", index: true, comment: "医院名称拼音首字母" },
|
||||
province: { type: String, default: "", index: true, comment: "省份" },
|
||||
city: { type: String, default: "", index: true, comment: "城市" },
|
||||
address: { type: String, default: "", comment: "医院地址" },
|
||||
phone: { type: String, default: "", comment: "联系电话" },
|
||||
departments: { type: [String], default: [], comment: "科室名称列表" },
|
||||
level: { type: String, default: "", comment: "医院等级,如 三级甲等" },
|
||||
fudanRank: {
|
||||
type: Number,
|
||||
default: DEFAULT_FUDAN_RANK,
|
||||
index: true,
|
||||
comment: "复旦综合排行榜档位,1 最高;未上榜为默认值",
|
||||
},
|
||||
fudanGrade: { type: String, default: "", comment: "复旦综合排行榜等级,如 A+++++" },
|
||||
meta: {
|
||||
createtime: { type: Date, default: Date.now, comment: "创建时间" },
|
||||
updatetime: { type: Date, default: Date.now, comment: "更新时间" },
|
||||
},
|
||||
},
|
||||
{ minimize: false, strict: false, collection: "hospital", timestamps: false }
|
||||
);
|
||||
|
||||
// 名称唯一:分院靠 name 区分,重名会互相污染。
|
||||
// 用命名索引,避免与历史遗留的 name_1 非唯一索引同名冲突
|
||||
HospitalSchema.index({ name: 1 }, { unique: true, name: "uniq_hospital_name" });
|
||||
|
||||
// ==================== 拼音生成 ====================
|
||||
|
||||
// 根据名称生成全拼与首字母(小写、无分隔)
|
||||
const buildPinyinFields = (name) => {
|
||||
const text = String(name || "");
|
||||
return {
|
||||
pinyin: pinyin(text, { toneType: "none", nonZh: "consecutive" }).toLowerCase().replace(/[^a-z0-9]/g, ""),
|
||||
pinyinFL: pinyin(text, { pattern: "first", toneType: "none", nonZh: "consecutive" }).toLowerCase().replace(/[^a-z0-9]/g, ""),
|
||||
};
|
||||
};
|
||||
|
||||
// 名称分隔符:兼容中文输入法下常见的横线写法
|
||||
const ENTITY_SEPARATOR = /[--—–]/;
|
||||
|
||||
// 从「主体名称-分院名称」中取主体名称;没有分隔符(独立医院)时返回整个名称
|
||||
const deriveEntityName = (name) => {
|
||||
const text = String(name || "").trim();
|
||||
if (!text) return "";
|
||||
const index = text.search(ENTITY_SEPARATOR);
|
||||
return index > 0 ? text.slice(0, index).trim() : text;
|
||||
};
|
||||
|
||||
// 保存时自动生成主体名称与拼音字段
|
||||
HospitalSchema.pre("save", function (next) {
|
||||
const name = String(this.name || "").trim();
|
||||
if (!String(this.entityName || "").trim()) this.entityName = deriveEntityName(name);
|
||||
if (this.isModified("name") || !this.pinyin || !this.pinyinFL) {
|
||||
const fields = buildPinyinFields(name);
|
||||
this.pinyin = fields.pinyin;
|
||||
this.pinyinFL = fields.pinyinFL;
|
||||
}
|
||||
|
||||
const fudan = resolveFudanRank([this.entityName, name]);
|
||||
this.fudanRank = fudan ? fudan.rank : DEFAULT_FUDAN_RANK;
|
||||
this.fudanGrade = fudan ? fudan.grade : "";
|
||||
next();
|
||||
});
|
||||
|
||||
// ==================== 静态方法 ====================
|
||||
|
||||
// 关键词 → 不区分大小写的包含匹配正则(转义特殊字符,避免查询报错或 ReDoS)
|
||||
const toRegex = (value) => ({
|
||||
$regex: String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"),
|
||||
$options: "i",
|
||||
});
|
||||
|
||||
// 搜索词限长,避免超长正则拖慢查询
|
||||
const MAX_SEARCH_LENGTH = 50;
|
||||
const normalizeSearch = (value) => String(value ?? "").trim().slice(0, MAX_SEARCH_LENGTH);
|
||||
|
||||
/**
|
||||
* 查询医院列表(支持分页、关键词与主体名称筛选)
|
||||
* keyword 同时匹配名称、主体名称、全拼与拼音首字母;
|
||||
* entityName 对主体名称做包含匹配,用于列出同一主体的所有分院/院区。
|
||||
* @returns {Promise<Object>} `{ list, total, page, pageSize }`
|
||||
*/
|
||||
HospitalSchema.statics.findHospitals = async function (options = {}) {
|
||||
const { page = 1, pageSize = 20 } = options;
|
||||
const keyword = normalizeSearch(options.keyword);
|
||||
const entityName = normalizeSearch(options.entityName);
|
||||
const filter = {};
|
||||
|
||||
if (entityName) filter.entityName = toRegex(entityName);
|
||||
if (keyword) {
|
||||
const re = toRegex(keyword);
|
||||
filter.$or = [{ name: re }, { entityName: re }, { pinyin: re }, { pinyinFL: re }];
|
||||
}
|
||||
|
||||
const skip = (page - 1) * pageSize;
|
||||
const [list, total] = await Promise.all([
|
||||
// 复旦榜上榜医院优先,同档按拼音排序;未上榜的默认值排在最后
|
||||
this.find(filter).sort({ fudanRank: 1, pinyin: 1, name: 1 }).skip(skip).limit(pageSize).exec(),
|
||||
this.countDocuments(filter).exec(),
|
||||
]);
|
||||
|
||||
return { list, total, page, pageSize };
|
||||
};
|
||||
|
||||
// 根据ID查找医院
|
||||
HospitalSchema.statics.findHospitalById = async function (id) {
|
||||
return await this.findById(id).exec();
|
||||
};
|
||||
|
||||
// 创建医院
|
||||
HospitalSchema.statics.createHospital = async function (data) {
|
||||
data.meta = { createtime: Date.now(), updatetime: Date.now() };
|
||||
const doc = new this(data);
|
||||
return await doc.save();
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据ID更新医院
|
||||
* 名称变更时同步拼音;主体名称显式传空时回退为名称前缀。
|
||||
* 未显式传主体名称时,仅当旧主体名称也是自动派生值才跟随新名称,
|
||||
* 避免覆盖人工指定的主体(如把独立医院并入某主体)。
|
||||
*/
|
||||
HospitalSchema.statics.updateHospitalById = async function (id, update) {
|
||||
if (update.name !== undefined) {
|
||||
const name = String(update.name ?? "").trim();
|
||||
update.name = name;
|
||||
Object.assign(update, buildPinyinFields(name));
|
||||
}
|
||||
|
||||
if (update.entityName !== undefined) {
|
||||
const entityName = String(update.entityName ?? "").trim();
|
||||
if (entityName) {
|
||||
update.entityName = entityName;
|
||||
} else if (update.name !== undefined) {
|
||||
update.entityName = deriveEntityName(update.name);
|
||||
} else {
|
||||
// 只清空主体名称、没带名称时,用库里现有名称回退
|
||||
const current = await this.findById(id).select("name").lean();
|
||||
update.entityName = deriveEntityName(current?.name);
|
||||
}
|
||||
} else if (update.name !== undefined) {
|
||||
// 名称变了但没传主体名称:旧主体名称是自动派生的,才跟着新名称一起变
|
||||
const current = await this.findById(id).select("name entityName").lean();
|
||||
if (current && current.entityName === deriveEntityName(current.name)) {
|
||||
update.entityName = deriveEntityName(update.name);
|
||||
}
|
||||
}
|
||||
|
||||
// 名称或主体名称变更后重算复旦榜档位;未上榜写默认值
|
||||
if (update.name !== undefined || update.entityName !== undefined) {
|
||||
const current = await this.findById(id).select("name entityName").lean();
|
||||
const finalName = update.name !== undefined ? update.name : current?.name;
|
||||
const finalEntityName = update.entityName !== undefined ? update.entityName : current?.entityName;
|
||||
const fudan = resolveFudanRank([finalEntityName, finalName]);
|
||||
update.fudanRank = fudan ? fudan.rank : DEFAULT_FUDAN_RANK;
|
||||
update.fudanGrade = fudan ? fudan.grade : "";
|
||||
}
|
||||
|
||||
update["meta.updatetime"] = Date.now();
|
||||
return await this.findByIdAndUpdate(id, { $set: update }, { new: true, runValidators: true }).exec();
|
||||
};
|
||||
|
||||
// 根据ID删除医院
|
||||
HospitalSchema.statics.deleteHospitalById = async function (id) {
|
||||
return await this.findByIdAndDelete(id).exec();
|
||||
};
|
||||
|
||||
export { HospitalSchema, DEFAULT_FUDAN_RANK, resolveFudanRank };
|
||||
@@ -5,6 +5,7 @@ import { HandlerResource } from "../handler/resource.js";
|
||||
import { HandlerEmployee } from "../handler/employee.js";
|
||||
import { HandlerAIMedia } from "../handler/ai_media.js";
|
||||
import { HandlerTrainingApplication } from "../handler/training_application.js";
|
||||
import { HandlerHospital } from "../handler/hospital.js";
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
import { getUserByToken } from "../utils/user_service.js";
|
||||
import { isAdmin } from "../utils/permissions.js";
|
||||
@@ -79,6 +80,7 @@ function registerRoutes(app) {
|
||||
const handlerEmployee = new HandlerEmployee();
|
||||
const handlerAIMedia = new HandlerAIMedia();
|
||||
const handlerTrainingApplication = new HandlerTrainingApplication();
|
||||
const handlerHospital = new HandlerHospital();
|
||||
|
||||
// 敏感数据路由需要登录后访问
|
||||
router.get("/escort-record/my", requireAuth, handlerEscortRecord.getMyRecords.bind(handlerEscortRecord));
|
||||
@@ -112,6 +114,13 @@ function registerRoutes(app) {
|
||||
router.put("/health-profile/:id", requireAuth, requireAdmin, handlerHealthProfile.updateProfile.bind(handlerHealthProfile));
|
||||
router.delete("/health-profile/:id", requireAuth, requireAdmin, handlerHealthProfile.deleteProfile.bind(handlerHealthProfile));
|
||||
|
||||
// 医院基础信息:列表/详情公开,写接口仅管理员
|
||||
router.get("/hospital", handlerHospital.getHospitals.bind(handlerHospital));
|
||||
router.get("/hospital/:id", handlerHospital.getHospitalById.bind(handlerHospital));
|
||||
router.post("/hospital", requireAuth, requireAdmin, createLimit, handlerHospital.createHospital.bind(handlerHospital));
|
||||
router.put("/hospital/:id", requireAuth, requireAdmin, updateLimit, handlerHospital.updateHospital.bind(handlerHospital));
|
||||
router.delete("/hospital/:id", requireAuth, requireAdmin, deleteLimit, handlerHospital.deleteHospital.bind(handlerHospital));
|
||||
|
||||
router.get("/service", handlerResource.getServices.bind(handlerResource));
|
||||
router.get("/agreement", handlerResource.getAgreement.bind(handlerResource));
|
||||
router.get("/hospital-info", handlerResource.getHospitalInfo.bind(handlerResource));
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* 一次性回填:按复旦综合排行榜给存量医院写入 fudanRank / fudanGrade。
|
||||
*
|
||||
* 用法:在 api/health 下执行 `node scripts/backfill_hospital_fudan_rank.js`
|
||||
* 未上榜医院写默认档位 999,保证接口排序时排在所有上榜医院之后。
|
||||
*/
|
||||
import { DBModel } from "../models/index.js";
|
||||
import { DEFAULT_FUDAN_RANK, resolveFudanRank } from "../models/schema/hospital.js";
|
||||
|
||||
DBModel.init();
|
||||
const conn = DBModel.dbConnection;
|
||||
|
||||
async function backfill() {
|
||||
const hospitals = await DBModel.Hospital.find(
|
||||
{},
|
||||
{ name: 1, entityName: 1, fudanRank: 1, fudanGrade: 1 }
|
||||
).lean();
|
||||
|
||||
const operations = [];
|
||||
let ranked = 0;
|
||||
|
||||
for (const hospital of hospitals) {
|
||||
const fudan = resolveFudanRank([hospital.entityName, hospital.name]);
|
||||
const rank = fudan ? fudan.rank : DEFAULT_FUDAN_RANK;
|
||||
const grade = fudan ? fudan.grade : "";
|
||||
if (fudan) ranked += 1;
|
||||
|
||||
if (hospital.fudanRank === rank && hospital.fudanGrade === grade) continue;
|
||||
|
||||
operations.push({
|
||||
updateOne: {
|
||||
filter: { _id: hospital._id },
|
||||
update: { $set: { fudanRank: rank, fudanGrade: grade } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (operations.length > 0) {
|
||||
await DBModel.Hospital.bulkWrite(operations);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`backfilled: total=${hospitals.length}, ranked=${ranked}, updated=${operations.length}`
|
||||
);
|
||||
await conn.close();
|
||||
}
|
||||
|
||||
if (conn.readyState === 1) {
|
||||
backfill().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
conn.once("connected", () => {
|
||||
backfill().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
conn.once("error", (error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user