From 45a0ba031e6d453f26b0e4ca181ebed4e119f829 Mon Sep 17 00:00:00 2001
From: chenyc <501753378@qq.com>
Date: 星期一, 23 十二月 2024 11:49:27 +0800
Subject: [PATCH] 缓存接口请求
---
app.js | 287 ++++++++++++++++-------------------
package.json | 1
thirdPartyApi.js | 145 ++++++++++++++++++
3 files changed, 279 insertions(+), 154 deletions(-)
diff --git a/app.js b/app.js
index cda3bb2..8772d10 100644
--- a/app.js
+++ b/app.js
@@ -5,12 +5,19 @@
const fs2=require('fs')
const path = require('path');
const moment = require('moment')
+const axios = require('axios');
// 转成能识别的url
const ViapiUtil = require('@alicloud/viapi-utils');
const facebody20191230 = require('@alicloud/facebody20191230');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
+const thirdPartyApi = require('./thirdPartyApi');
+
+/**token缓存 */
+let cachedToken = null;
+/**token缓存时间 */
+let tokenExpiresAt = null;
const app = express();
const port = 3000;
@@ -78,35 +85,34 @@
const xid = req.body.xid;
console.log(`action=${action},deviceID=${deviceID},type=${type},xid=${xid}`)
if (action === 'doWebUser' && deviceID && type !== undefined) {
- let query = `SELECT * FROM patient_info WHERE code = '${xid}'`
try {
- const [rows] = await pool.promise().query(query);
- if (rows.length > 0) {
- const user = rows[0];
- const response = {
- retCode: "1",
- uinfo: {
- title: user.client_code,
- cardID: user.code,
- userNum: user.patient_no,
- name: user.patient_name,
- sex: user.patient_gender === 0 ? '男' : '女',
- age: getAgeFromIdCard(user.patient_identity_no),
- headimgurl: user.patient_avatar_icon,
- imgBaseData: '',
- remark: ''
+ const pathParams={code:xid}
+ const data = await thirdPartyApi.fetchThirdPartyData('/patient/info/detail2', 'POST', {}, null, pathParams,{});
+ console.log('--------------获取到了患者信息',data.data)
+ // console.log(data)
+ if(data?.code===200&&data?.message==='SUCCESS'&&data?.data){
+ const user = data.data;
+ response = {
+ recode: 2001,
+ userinfo: {
+ name: user.patientName,
+ sex: user.patientGenderText,
+ age: user.age,
+ usernum: user.code, //这个是数据返回会携带回来UID
+ address: user.patientAddress,
+ remark: '患者人脸识别111'
},
- dbinfo: {}, // 如果没有需要更新的数据库信息,可以保持空
- msg: "success"
+ remsg: "success"
};
- res.json(response);
- } else {
- const response = {
- retCode: "0",
- msg: "没有找到患者,请先检查患者code"
+ console.log('返回患者信息成功')
+ }else{
+ response = {
+ retcode: 1001,
+ remsg: "没有找到患者,请先检查患者code"
};
- res.json(response);
}
+ res.json(response);
+
} catch (err) {
console.error(err);
res.status(500).json({ retCode: "-1", msg: "Database error" });
@@ -121,34 +127,31 @@
logHttps(mode)
const patientId = req.query.patientId;
if (patientId) {
- let query = `SELECT * FROM patient_info WHERE code = '${xid}'`
try {
- const [rows] = await pool.promise().query(query);
- if (rows.length > 0) {
- const user = rows[0];
- const response = {
- retCode: "1",
- uinfo: {
- title: user.client_code,
- cardID: user.code,
- userNum: user.patient_no,
- name: user.patient_name,
- sex: user.patient_gender === 0 ? '男' : '女',
- age: getAgeFromIdCard(user.patient_identity_no),
- headimgurl: user.patient_avatar_icon,
- imgBaseData: '',
- remark: ''
+ const pathParams={code:xid}
+ const data = await thirdPartyApi.fetchThirdPartyData('/patient/info/detail2', 'POST', {}, null, pathParams,{});
+ console.log('--------------获取到了患者信息')
+ // console.log(data)
+ if(data?.code===200&&data?.message==='SUCCESS'&&data?.data){
+ const user = data.data;
+ response = {
+ recode: 2001,
+ userinfo: {
+ name: user.patientName,
+ sex: user.patientGenderText,
+ age: user.age,
+ usernum: user.code, //这个是数据返回会携带回来UID
+ address: user.patientAddress,
+ remark: '患者人脸识别111'
},
- dbinfo: {}, // 如果没有需要更新的数据库信息,可以保持空
- msg: "success"
+ remsg: "success"
};
- res.json(response);
- } else {
- const response = {
- retCode: "0",
- msg: "没有找到患者,请先检查患者code"
+ console.log('返回患者信息成功')
+ }else{
+ response = {
+ retcode: 1001,
+ remsg: "没有找到患者,请先检查患者code"
};
- res.json(response);
}
} catch (err) {
console.error(err);
@@ -197,28 +200,32 @@
} else if (faceItems[0].score >= 0.2) {
const entityId = faceItems[0].entityId
console.log(entityId, '患者id找到了')
- let query = `SELECT * FROM patient_info WHERE code = '${entityId}'`
- const [rows] = await pool.promise().query(query);
- if (rows.length > 0) {
- const user = rows[0];
+ const pathParams={code:entityId}
+ const data = await thirdPartyApi.fetchThirdPartyData('/patient/info/detail2', 'POST', {}, null, pathParams,{});
+ console.log('--------------获取到了患者信息')
+ // console.log(data)
+ if(data?.code===200&&data?.message==='SUCCESS'&&data?.data){
+ const user = data.data;
response = {
recode: 2001,
userinfo: {
- name: user.patient_name,
- sex: user.patient_gender === 0 ? '男' : '女',
- age: getAgeFromIdCard(user.patient_identity_no),
+ name: user.patientName,
+ sex: user.patientGenderText,
+ age: user.age,
usernum: user.code, //这个是数据返回会携带回来UID
- address: user.patient_address,
+ address: user.patientAddress,
remark: '患者人脸识别111'
},
remsg: "success"
};
- } else {
+ console.log('返回患者信息成功')
+ }else{
response = {
retcode: 1001,
remsg: "没有找到患者,请先检查患者code"
};
}
+
} else {
response = {
retcode: 1001,
@@ -258,10 +265,35 @@
mode.action='webResults'
logHttps(mode)
try {
-
+
const datas=mode.datas
datas.forEach(async element => {
- await installData(element)
+ // 组合数据
+ let data={}
+ // 没有BF
+ if(element.fatFree){
+ data={
+ id:0,
+ code:element.recordNo,
+ patientCode:element.userID,
+ commTime:element.measureTime,
+ rtcfJsonBf:JSON.stringify(element)
+ }
+ }
+ // 没有BMI
+ if(element.bmi){
+ data={
+ id:0,
+ code:element.recordNo,
+ patientCode:element.userID,
+ commTime:element.measureTime,
+ rtcfJsonBmi:JSON.stringify(element)
+ }
+ }
+ console.log(data)
+ const resdata = await thirdPartyApi.fetchThirdPartyData('/patient/rtcf/result/save', 'POST', {}, data,{},{});
+ console.log('-----返回人体成分分析保存')
+ console.log(resdata)
});
response = {
recode: "2000",
@@ -287,25 +319,28 @@
logHttps(mode)
if(patientId&&clientCode){
// 输出传入的patientid值
- console.log('Patient ID:',patientId)
- let query = `SELECT * FROM patient_info WHERE patient_name_py LIKE '${patientId}' AND client_code = '${clientCode}'`
- console.log(query)
try {
- const [rows] = await pool.promise().query(query);
+ //查询参数
+ const pathParams={
+ clientCode:clientCode,
+ patQueryCode:patientId
+ }
+ const data = await thirdPartyApi.fetchThirdPartyDataNoToke('/patient/info/listPatsPublic', 'POST', {}, null, pathParams,{});
+ console.log(data.data.list)
+ const rows= data.data.list
if (rows.length > 0) {
- // const user = rows[0];
let users=[]
rows.forEach(user=>{
users.push({
patientId: user.code,
- fullName: user.patient_name,
- gender: user.patient_gender,
- age: getAgeFromIdCard(user.patient_identity_no),
+ fullName: user.patientName,
+ gender: user.patientGender,
+ age: user.age,
birthday:'',
- phoneNum:user.patient_mobile,
- address: user.patient_avatar_icon,
- idType: user.patient_identity_type,
- idNum: user.patient_identity_no,
+ phoneNum:user.patientMobile,
+ address: user.patientAvatarIcon,
+ idType: user.patientIdentityType,
+ idNum: user.patientIdentityNo,
height:'',
weight:'',
requestDoctor:'',
@@ -325,33 +360,39 @@
}
} catch (err) {
console.error(err);
- res.status(500).json({ retCode: "-1", msg: "Database error" });
+ res.status(500).json({ retCode: "-1", msg: "接口出错!"+err });
}
}else{
// 如果请求参数不符合预期,则返回错误信息
- res.status(400).json({ retCode: "-1", msg: "Invalid request parameters333" });
+ res.status(400).json({ retCode: "-1", msg: "请求参数出错" });
}
})
/**
* PostCheckExam 病人信息及检测结果以JSON的形式回传至服务器
*/
-app.post('/PostCheckExam',(req,res)=>{
+app.post('/PostCheckExam',async (req,res)=>{
try {
- const mode={
- action:'PostCheckExam',
- params:'jjjj'
+ const clientCode = req.query.clientCode;
+ console.log('-------------------',clientCode)
+ if(!clientCode){
+ res.json({"Msg": "请求参数没有clientCode", "Status": "err" });
+ return
}
- logHttps(mode)
- // 查看body参数
const body=req.body
console.log(body)
+ const mode={
+ action:'PostCheckExam',
+ params:body.examId
+ }
+ logHttps(mode)
+ // 组合上传数据
const data={
id:0,
- code:body.examId,
+ code:'',
patient_code :body.patientId,
- client_code:'',
+ client_code:clientCode,
exam_id:body.examId,
SBPLB:body.SBPLB,
MBPLB:body.MBPLB,
@@ -412,15 +453,13 @@
abi_advice:body.abiAdvice,
pwv_result:body.pwvResult
}
- const { query, params } = createInsertQuery('patient_result_from_doppler_blood_flow_device', data);
- pool.query(query, params, (error, results) => {
- if (error) {
- console.error('Error inserting data:', error);
- return res.status(500).json({Status:'error', Msg: '数据库错误'+error });
- }
-
- res.json({ Status:'SUCCESS',Msg: '插入成功'+ results.insertId });
- });
+ const resdata = await thirdPartyApi.fetchThirdPartyDataNoToke('/patient/result/from/doppler/blood/flow/device/saveData', 'POST', {}, data,{},{});
+ console.log(resdata)
+ if(resdata.code===200&&resdata?.data=='OK'){
+ res.json({"Msg": "检查结果上传成功", "Status": "SUCCESS" });
+ }else{
+ res.json({"Msg": "检查结果上传失败", "Status": "err" });
+ }
}
catch(err){
console.log(err)
@@ -435,25 +474,6 @@
app.listen(port, async () => {
console.log(`Server running at http://localhost:${port}/`);
});
-/**
- *
- * @param {表名称} tableName
- * @param {表列内容} data
- * @returns
- */
-const createInsertQuery=(tableName, data) =>{
- const columns = Object.keys(data).map(key => `\`${key}\``).join(', ');
- const placeholders = Object.keys(data).map(() => '?').join(', ');
-
- const query = `INSERT INTO \`${tableName}\` (${columns}) VALUES (${placeholders})`;
-
- // 返回查询字符串和参数数组
- return {
- query,
- params: Object.values(data)
- };
-}
-
/**
*
* @param {*} file base64图片格式转本地
@@ -512,50 +532,10 @@
console.error('访问日志记录错误:', err);
}
}
-// 插入数据
-const installData=async (mode)=>{
- console.log(mode)
- try{
- let selectSql=`SELECT * FROM patient_rtcf_result WHERE code='${mode.recordNo}'`
- const [rows] = await pool.promise().query(selectSql);
- if(rows.length>0){
- let updateSql=''
- if(mode.fatFree){
- updateSql=`UPDATE patient_rtcf_result SET rtcf_json_bf ='${JSON.stringify(mode)}'`
- }else if (mode.bmi){
- updateSql=`UPDATE patient_rtcf_result SET rtcf_json_bmi ='${JSON.stringify(mode)}'`
- }
- if(updateSql){
- console.log(`-------------------------更新${updateSql}---------`)
- console.log(updateSql)
- await pool.promise().query(updateSql)
- }
- }else{
- console.log('34')
- // 临时的人体成分分析
- let bf=''
- // 临时的身高体重
- let bmi=''
- if(mode.fatFree){
- bf=JSON.stringify(mode)
- }
- if(mode.bmi){
- bmi=JSON.stringify(mode)
- }
- console.log(`bf=${bf},bmi=====${bmi}`)
- let sqlStr=`INSERT INTO patient_rtcf_result (id, code, patient_code,`+
- `comm_time,rtcf_json_bmi,`+
- `rtcf_json_bf,`+
- `create_time)`+
- `VALUES (0, '${mode.recordNo}', '${mode.userID}', '${mode.measureTime}','${bmi}','${bf}','${moment(new Date()).format('YYYY-MM-DD HH:mm:ss')}')`
- console.log(sqlStr)
- await pool.promise().query(sqlStr)
- }
-
- }catch(err){
- console.log('数据写入异常22')
- }
-}
+
+/**
+ * 根据身份证算年龄
+ */
function getAgeFromIdCard(idCard) {
// 检查身份证号码长度是否正确
@@ -584,4 +564,3 @@
return age;
}
-
diff --git a/package.json b/package.json
index 4fa3855..f80bd86 100644
--- a/package.json
+++ b/package.json
@@ -16,6 +16,7 @@
"dependencies": {
"@alicloud/facebody20191230": "^5.1.2",
"@alicloud/viapi-utils": "^1.0.0",
+ "axios": "^1.7.9",
"body-parser": "^1.20.3",
"express": "^4.21.1",
"moment": "^2.30.1",
diff --git a/thirdPartyApi.js b/thirdPartyApi.js
new file mode 100644
index 0000000..b47505b
--- /dev/null
+++ b/thirdPartyApi.js
@@ -0,0 +1,145 @@
+// thirdPartyApi.js
+const axios = require('axios');
+// BASIC_API = 'https://hemobs.icoldchain.cn/'
+const BASIC_API = 'http://testbs.ihemodialysis.com/'
+let cachedToken = null;
+let tokenExpiresAt = null;
+
+// 获取 Token 的函数
+async function getAccessToken() {
+ try {
+ const formData = new FormData();
+ formData.append('user_no', 'data_cyc');
+ formData.append('user_password', 'cheng0624');
+ const response = await axios.post(`${BASIC_API}/user/info/login`, formData, {
+ headers: {
+ 'Content-Type': 'multipart/form-data', // 通常不需要手动设置,axios 会自动处理
+ }
+ });
+ // 假设响应中包含 token 字段和 expires_in 秒数
+ const { data } = response.data;
+ const expires_in=3600
+ return { data ,expires_in};
+ } catch (error) {
+ console.error('Error getting access token:', error.message);
+ throw error;
+ }
+}
+
+// 获取缓存或新的 Token
+async function getCachedOrNewToken() {
+ if (cachedToken && tokenExpiresAt > Date.now()) {
+ return cachedToken;
+ }
+
+ // 如果 token 已经过期或不存在,则重新获取
+ const { data, expires_in } = await getAccessToken();
+ cachedToken = data;
+ tokenExpiresAt = Date.now() + (expires_in - 60) * 1000; // 提前 60 秒刷新 token
+ return cachedToken;
+}
+
+// 构建 URL 函数
+function buildUrl(base, pathParams) {
+ let url = BASIC_API+base;
+ Object.keys(pathParams).forEach(key => {
+ url = url.replace(`:${key}`, encodeURIComponent(pathParams[key]));
+ });
+ return url;
+}
+
+// 发起第三方 API 请求 不需要token
+async function fetchThirdPartyDataNoToke(url, method = 'GET', headers = {}, data = null, queryParams = {}, pathParams = {}) {
+ try {
+ const fullUrl = buildUrl(url, pathParams);
+ const response = await axios({
+ url: fullUrl,
+ method,
+ headers: {
+ ...headers
+ },
+ params: queryParams, // 查询字符串参数
+ data // 请求体参数
+ });
+
+ return response.data;
+ } catch (error) {
+ console.error('Error fetching third-party data:', error.message);
+ throw error;
+ }
+}
+
+// 发起第三方 API 请求
+async function fetchThirdPartyData(url, method = 'GET', headers = {}, data = null, queryParams = {}, pathParams = {}) {
+ try {
+ const token = await getCachedOrNewToken();
+ console.log('得到了token------------------------',token)
+ const fullUrl = buildUrl(url, pathParams);
+
+ const response = await axios({
+ url: fullUrl,
+ method,
+ headers: {
+ ...headers,
+ Authorization: `Bearer ${token}`
+ },
+ params: queryParams, // 查询字符串参数
+ data // 请求体参数
+ });
+
+ return response.data;
+ } catch (error) {
+ console.error('Error fetching third-party data:', error.message);
+ throw error;
+ }
+}
+
+module.exports = {
+ fetchThirdPartyDataNoToke,
+ fetchThirdPartyData
+};
+
+// 插入数据
+const installData=async (mode)=>{
+ console.log(mode)
+ try{
+ let selectSql=`SELECT * FROM patient_rtcf_result WHERE code='${mode.recordNo}'`
+ const [rows] = await pool.promise().query(selectSql);
+ if(rows.length>0){
+ let updateSql=''
+ if(mode.fatFree){
+ updateSql=`UPDATE patient_rtcf_result SET rtcf_json_bf ='${JSON.stringify(mode)}'`
+ }else if (mode.bmi){
+ updateSql=`UPDATE patient_rtcf_result SET rtcf_json_bmi ='${JSON.stringify(mode)}'`
+ }
+ if(updateSql){
+ console.log(`-------------------------更新${updateSql}---------`)
+ console.log(updateSql)
+ await pool.promise().query(updateSql)
+ }
+ }else{
+ console.log('34')
+ // 临时的人体成分分析
+ let bf=''
+ // 临时的身高体重
+ let bmi=''
+ if(mode.fatFree){
+ bf=JSON.stringify(mode)
+ }
+ if(mode.bmi){
+ bmi=JSON.stringify(mode)
+ }
+ console.log(`bf=${bf},bmi=====${bmi}`)
+ let sqlStr=`INSERT INTO patient_rtcf_result (id, code, patient_code,`+
+ `comm_time,rtcf_json_bmi,`+
+ `rtcf_json_bf,`+
+ `create_time)`+
+ `VALUES (0, '${mode.recordNo}', '${mode.userID}', '${mode.measureTime}','${bmi}','${bf}','${moment(new Date()).format('YYYY-MM-DD HH:mm:ss')}')`
+ console.log(sqlStr)
+ await pool.promise().query(sqlStr)
+ }
+
+ }catch(err){
+ console.log('数据写入异常22')
+ }
+}
\ No newline at end of file
--
Gitblit v1.8.0