增加健康档案api

This commit is contained in:
lik
2026-08-27 21:54:51 +08:00
parent 1f10eb3c92
commit 644f4bc7cb
4 changed files with 255 additions and 0 deletions
+96
View File
@@ -0,0 +1,96 @@
import { DBModel } from "../models/index.js";
import ResponseUtil from "../utils/responseUtil.js";
class HandlerHealthProfile {
constructor() {
}
async getProfiles(ctx) {
try {
const { page = 1, pageSize = 20, userId, name, mobile, sortBy } = ctx.request.query;
const result = await DBModel.HealthProfile.findProfiles({
page: parseInt(page),
pageSize: parseInt(pageSize),
userId,
name,
mobile,
sortBy,
});
return ResponseUtil.success(ctx, result, "查询成功");
} catch (err) {
return ResponseUtil.internalError(ctx, err.message);
}
}
async getProfileById(ctx) {
try {
const { id } = ctx.params;
if (!id) {
return ResponseUtil.badRequest(ctx, "缺少档案ID");
}
const profile = await DBModel.HealthProfile.findProfileById(id);
if (!profile) {
return ResponseUtil.notFound(ctx, "健康档案不存在");
}
return ResponseUtil.success(ctx, { profile }, "查询成功");
} catch (err) {
return ResponseUtil.internalError(ctx, err.message);
}
}
async createProfile(ctx) {
try {
const body = ctx.request.body;
const newProfile = await DBModel.HealthProfile.createProfile(body);
return ResponseUtil.success(ctx, { profile: newProfile }, "创建成功");
} catch (err) {
return ResponseUtil.internalError(ctx, err.message);
}
}
async updateProfile(ctx) {
try {
const { id } = ctx.params;
const update = ctx.request.body;
if (!id) {
return ResponseUtil.badRequest(ctx, "缺少档案ID");
}
const updatedProfile = await DBModel.HealthProfile.updateProfileById(id, update);
if (!updatedProfile) {
return ResponseUtil.notFound(ctx, "健康档案不存在");
}
return ResponseUtil.success(ctx, { profile: updatedProfile }, "更新成功");
} catch (err) {
return ResponseUtil.internalError(ctx, err.message);
}
}
async deleteProfile(ctx) {
try {
const { id } = ctx.params;
if (!id) {
return ResponseUtil.badRequest(ctx, "缺少档案ID");
}
const deletedProfile = await DBModel.HealthProfile.deleteProfileById(id);
if (!deletedProfile) {
return ResponseUtil.notFound(ctx, "健康档案不存在");
}
return ResponseUtil.success(ctx, { profile: deletedProfile }, "删除成功");
} catch (err) {
return ResponseUtil.internalError(ctx, err.message);
}
}
}
export { HandlerHealthProfile };
+3
View File
@@ -3,6 +3,7 @@
import mongoose from 'mongoose';
import { EscortRecordSchema } from "./schema/escort_record.js"
import { OrganizationSchema } from "./schema/org.js"
import { HealthProfileSchema } from "./schema/health_profile.js"
import config from '../conf.json' with { type: 'json' };
import logger from '../utils/logger.js';
@@ -12,6 +13,7 @@ class MongoDBSchema {
this.User = null;
this.EscortRecord = null;
this.Organization = null;
this.HealthProfile = null;
}
init() {
@@ -38,6 +40,7 @@ class MongoDBSchema {
);
this.EscortRecord = this.dbConnection.model('escort_record', EscortRecordSchema)
this.HealthProfile = this.dbConnection.model('health_profile', HealthProfileSchema)
}
}
+148
View File
@@ -0,0 +1,148 @@
"use strict";
import mongoose from "mongoose";
/**
* HealthProfile Schema
* 健康档案 - 记录患者的基本健康信息,内容保持简单
*/
const HealthProfileSchema = mongoose.Schema(
{
// 关联用户ID(可为空)
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
index: { unique: false, sparse: true },
comment: "所属用户ID",
},
// 患者信息
profile: {
name: { type: String, default: "", comment: "患者姓名" },
mobile: { type: String, default: "", index: true, comment: "患者电话" },
sex: { type: String, enum: ["male", "female", ""], default: "", comment: "性别" },
age: { type: Number, default: 0, comment: "年龄" },
idnumber: { type: String, default: "", comment: "身份证号" },
},
// 健康信息
health: {
height: { type: Number, default: 0, comment: "身高(cm" },
weight: { type: Number, default: 0, comment: "体重(kg" },
bloodType: { type: String, default: "", comment: "血型" },
remark: { type: String, default: "", comment: "备注" },
},
// 元数据
meta: {
createtime: { type: Date, default: Date.now, comment: "创建时间" },
updatetime: { type: Date, default: Date.now, comment: "更新时间" },
},
},
{
minimize: false,
strict: false,
collection: "health_profile",
timestamps: false,
}
);
// ==================== 静态方法 ====================
/**
* 根据用户ID查找健康档案
*/
HealthProfileSchema.statics.findByUserId = async function (userId) {
return await this.findOne({ userId }).exec();
};
/**
* 查询健康档案列表(支持分页与筛选)
*
* @param {Object} options - 查询选项
* @param {number} [options.page=1] - 页码
* @param {number} [options.pageSize=20] - 每页数量
* @param {ObjectId} [options.userId] - 所属用户ID筛选(可选)
* @param {string} [options.name] - 患者姓名模糊筛选(可选)
* @param {string} [options.mobile] - 患者电话筛选(可选)
* @param {string} [options.sortBy="createtime"] - 排序字段:createtime | updatetime(可选)
* @returns {Promise<Object>} 返回 `{ list, total, page, pageSize }`
*/
HealthProfileSchema.statics.findProfiles = async function (options = {}) {
const { page = 1, pageSize = 20, userId, name, mobile, sortBy = "createtime" } = options;
const filter = {};
if (userId) {
filter.userId = userId;
}
if (name) {
filter["profile.name"] = { $regex: name, $options: "i" };
}
if (mobile) {
filter["profile.mobile"] = mobile;
}
const sortField = sortBy === "updatetime" ? "meta.updatetime" : "meta.createtime";
const skip = (page - 1) * pageSize;
const [list, total] = await Promise.all([
this.find(filter)
.sort({ [sortField]: -1 })
.skip(skip)
.limit(pageSize)
.exec(),
this.countDocuments(filter).exec(),
]);
return { list, total, page: parseInt(page), pageSize: parseInt(pageSize) };
};
/**
* 根据ID查找健康档案
*/
HealthProfileSchema.statics.findProfileById = async function (id) {
return await this.findById(id).exec();
};
/**
* 创建健康档案
*/
HealthProfileSchema.statics.createProfile = async function (data) {
data.meta = { createtime: Date.now(), updatetime: Date.now() };
const doc = new this(data);
return await doc.save();
};
/**
* 根据ID更新健康档案
*/
HealthProfileSchema.statics.updateProfileById = async function (id, update) {
update["meta.updatetime"] = Date.now();
return await this.findByIdAndUpdate(id, { $set: update }, { new: true }).exec();
};
/**
* 根据用户ID更新健康档案
*/
HealthProfileSchema.statics.updateProfile = async function (userId, update) {
update["meta.updatetime"] = Date.now();
return await this.findOneAndUpdate({ userId }, { $set: update }, { new: true }).exec();
};
/**
* 根据ID删除健康档案
*/
HealthProfileSchema.statics.deleteProfileById = async function (id) {
try {
return await this.findByIdAndDelete(id).exec();
} catch (error) {
console.error("删除健康档案失败:", error);
return null;
}
};
// ==================== 索引定义 ====================
HealthProfileSchema.index({ userId: 1 }, { sparse: true });
HealthProfileSchema.index({ "profile.mobile": 1 });
export { HealthProfileSchema };
+8
View File
@@ -1,5 +1,6 @@
import Router from "koa-router";
import { HandlerEscortRecord } from "../handler/escort_record.js";
import { HandlerHealthProfile } from "../handler/health_profile.js";
import { HandlerResource } from "../handler/resource.js";
function printRoutes(stack) {
@@ -15,6 +16,7 @@ function registerRoutes(app) {
const router = new Router({ prefix: '/health' });
const handlerEscortRecord = new HandlerEscortRecord();
const handlerHealthProfile = new HandlerHealthProfile();
const handlerResource = new HandlerResource();
router.get("/escort-record/my", handlerEscortRecord.getRecords.bind(handlerEscortRecord));
@@ -25,6 +27,12 @@ function registerRoutes(app) {
router.patch("/escort-record/:id/status", handlerEscortRecord.updateStatus.bind(handlerEscortRecord));
router.delete("/escort-record/:id", handlerEscortRecord.deleteRecord.bind(handlerEscortRecord));
router.get("/health-profile", handlerHealthProfile.getProfiles.bind(handlerHealthProfile));
router.get("/health-profile/:id", handlerHealthProfile.getProfileById.bind(handlerHealthProfile));
router.post("/health-profile", handlerHealthProfile.createProfile.bind(handlerHealthProfile));
router.put("/health-profile/:id", handlerHealthProfile.updateProfile.bind(handlerHealthProfile));
router.delete("/health-profile/:id", handlerHealthProfile.deleteProfile.bind(handlerHealthProfile));
router.get("/service", handlerResource.getServices.bind(handlerResource));
router.get("/agreement", handlerResource.getAgreement.bind(handlerResource));
router.get("/hospital-info", handlerResource.getHospitalInfo.bind(handlerResource));