Quellcode durchsuchen

增加依赖:bearcat, bluebird, mongoose;Redis客户端增加async调用

Sand vor 8 Jahren
Ursprung
Commit
a8746f052f

+ 8 - 1
src/server/include/commons.js

@ -76,4 +76,11 @@ exports.MAX_INT = 9007199254740992;
 *
 * @type {number}
 */
exports.DEFAULT_PAGE_SIZE = 100;
exports.DEFAULT_PAGE_SIZE = 100;
/**
 * Redis Key列表。
 */
exports.REDIS_KEYS = {
  Users: "users:"
};

+ 0 - 50
src/server/models/sync/user.synchronizer.js

@ -1,50 +0,0 @@
/**
 * 用户同步器,同步医生与患者数据。
 *
 * author: Sand
 * since: 12/9/2016
 */
"use strict";
let wlyyUserRepo = require('./../../repository/wlyy/wlyy.user.repo');
let SyncLog = require('./../../repository/sync.log');
let log = require("../../util/log");
class UserSynchronizer{
    constructor(){
    }
    /**
     * 同步用户列表。
     */
    static synchronizeUser(){
        let syncLog = new SyncLog();
        syncLog.getLastUserSynchronizeTime(function (err, res) {
            if(err) {
                log.error("User synchronize failed: ", err);
                return;
            }
            wlyyUserRepo.getUpdatedUsers(res.last_sync_time, function (err, res) {
                if(err) {
                    log.error("User synchronize failed: ", err);
                    return;
                }
                for(let i = 0; i < res.length; ++i){
                    let user = res[i];
                    if(user.type  === 'doctor'){
                    } else {
                    }
                }
                syncLog.updateUserSynchorizeLog(function (err, res) {
                    if(err) log.error("User synchronize failed: ", err);
                });
            });
        });
    }
}
module.exports = Users;

+ 15 - 15
src/server/models/doctor.js

@ -3,23 +3,23 @@
 */
"use strict";
let log = require("../util/log.js");
let log = require("../../util/log.js");
let getui = require('getui');
let BaseModel = require('./base.model');
let Schedule = require("./schedule/schedule.js");
let doctorRepo = require('../repository/doctor.repo.js');
let gmRepo = require('../repository/group.msg.repo');
let pmRepo = require('../repository/private.msg.repo');
let nmRepo = require("../repository/notify.msg.repo");
let smRepo = require("../repository/system.msg.repo.js");
let statsRepo = require("../repository/stats.msg.repo");
let objectUtil = require("../util/objectUtil.js");
let modelUtil = require('../util/modelUtil');
const CONTENT_TYPES = require('../include/commons').CONTENT_TYPE;
const PLATFORMS = require('../include/commons').PLATFORM;
const MAX_INT = require('../include/commons').MAX_INT;
let BaseModel = require('./../base.model');
let Schedule = require("./../schedule/schedule.js");
let doctorRepo = require('../../repository/doctor.repo.js');
let gmRepo = require('../../repository/group.msg.repo');
let pmRepo = require('../../repository/private.msg.repo');
let nmRepo = require("../../repository/notify.msg.repo");
let smRepo = require("../../repository/system.msg.repo.js");
let statsRepo = require("../../repository/stats.msg.repo");
let objectUtil = require("../../util/objectUtil.js");
let modelUtil = require('../../util/modelUtil');
const CONTENT_TYPES = require('../../include/commons').CONTENT_TYPE;
const PLATFORMS = require('../../include/commons').PLATFORM;
const MAX_INT = require('../../include/commons').MAX_INT;
class Doctor extends BaseModel {
    constructor() {

src/server/models/patient.js → src/server/models/user/patient.js


+ 64 - 0
src/server/models/user/users.js

@ -0,0 +1,64 @@
/**
 * 用户集合。管理Redis中的用户列表。
 *
 * author: Sand
 * since: 12/13/2016
 */
"use strict";
let RedisKeys = require('../../include/commons').REDIS_KEYS;
let BaseModel = require('../base.model');
let DoctorRepo = require('../../repository/mysql/doctor.repo');
let PatientRepo = require('../../repository/mysql/patient.repo');
let RedisClient = require('../../repository/redis/redis.client');
let redisConn = RedisClient.redisClient().connection;
let log = require('../../util/log');
let async = require('async');
var imDb = require('../../repository/mysql/db/im.db');
class Users extends BaseModel {
    constructor() {
        super();
        this._key = RedisKeys.Users;
    }
    getUser(userId) {
    }
    isPatientId(userId) {
        return async.waterfall([
                function (callback) {
                    var sql = "select case count(*) > 0 then true else false is_patient end c from patients where code = ?";
                    imDb.execQuery({
                        "sql": sql,
                        "args": [userId],
                        "handler": function (err, res) {
                            callback(null, res);
                        }
                    });
                    return false;
                },
                function (res, callback) {
                    callback(null, res.is_patient);
                }
            ],
            function (err, res) {
                if (err) {
                    log.error("User id probe failed: ", err);
                    return false;
                }
                return res;
            });
    }
}
module.exports = Users;

+ 3 - 0
src/server/package.json

@ -8,6 +8,8 @@
  },
  "dependencies": {
    "async": "~2.0.1",
    "bearcat": "^0.4.29",
    "bluebird": "^3.4.6",
    "body-parser": "~1.12.4",
    "cookie-parser": "~1.3.5",
    "cron-builder": "^0.3.0",
@ -15,6 +17,7 @@
    "express": "~4.12.4",
    "jade": "~1.9.2",
    "mocha": "~3.1.2",
    "mongoose": "^4.7.2",
    "morgan": "~1.5.3",
    "mysql": "~2.5.3",
    "node-schedule": "^1.2.0",

+ 3 - 3
src/server/repository/mysql/im.db.js

@ -1,10 +1,10 @@
"use strict";
var configFile = require('../../include/commons').CONFIG_FILE;
var config = require('../../resources/config/' + configFile);
var configFile = require('../../../include/commons').CONFIG_FILE;
var config = require('../../../resources/config/' + configFile);
var mysql = require('mysql');
var dbUtil = require('../../util/dbUtil');
var dbUtil = require('../../../util/dbUtil');
var pool = mysql.createPool(config.imDbConfig);

+ 18 - 23
src/server/repository/doctor.repo.js

@ -1,12 +1,11 @@
/**
 * 医生模型。医生真实数据存在于家庭医生平台数据库,即医生的ID,姓名,年龄等详细内容。而IM平台的user表只包含用户当前的在线状态,
 * 医生库。医生真实数据存在于家庭医生平台数据库,即医生的ID,姓名,年龄等详细内容。而IM平台的user表只包含用户当前的在线状态,
 * 即用户的准实时状态,token等内容,不包含用户具体的详细信息。
 */
"use strict";
var log = require('../util/log');
var imRepo = require("./mysql/im.db.js");
var wlyyRepo = require("./mysql/wlyy.db.js");
var imDb = require("./db/im.db.js");
var log = require('../../util/log');
class DoctorRepo {
    constructor() {
@ -16,47 +15,43 @@ class DoctorRepo {
    }
    static findOne(code, handler) {
        wlyyRepo.execQuery({
            "sql": "select code, name from doctors where code = ? ",
            "args": [code],
    static findOne(doctorId, handler) {
        imDb.execQuery({
            "sql": "select id, name, sex, birthdate, avatar, level from doctors where code = ? ",
            "args": [doctorId],
            "handler": handler
        });
    };
    /**
     * 判断用户是否存在。数据从家庭医生平台获取,而不是IM库的user表。
     * 判断用户是否存在。
     *
     * @param user
     * @param handler
     */
    static isExist(user, handler) {
        wlyyRepo.execQuery({
            "sql": "SELECT count(*) from wlyy_doctor WHERE code=?",
            "args": [user],
            "handler": handler
        });
    static isExist(doctorId, handler) {
    };
    static getUserStatus(userId, handler) {
        imRepo.execQuery({
    static getUserStatus(doctorId, handler) {
        imDb.execQuery({
            "sql": "SELECT platform,token,client_id,is_online,status from user WHERE user_id = ?",
            "args": [userId],
            "handler": handler
        });
    };
    static login(userId, token, client_id, platform, handler) {
        imRepo.execQuery({
    static login(doctorId, token, client_id, platform, handler) {
        imDb.execQuery({
            "sql": "INSERT INTO user (user_id,token,client_id,platform,is_online,status) VALUES (?,?,?,?,1,1) ON" +
            " DUPLICATE KEY UPDATE token=?,client_id=?,platform=?,is_online=1,status=1",
            "args": [userId, token, client_id, platform, token, client_id, platform],
            "args": [doctorId, token, client_id, platform, token, client_id, platform],
            "handler": handler
        });
    };
    static logout(userId, handler) {
        imRepo.execQuery({
        imDb.execQuery({
            "sql": "UPDATE user SET is_online='0',status='0' WHERE user_id=?",
            "args": [userId],
            "handler": handler
@ -64,7 +59,7 @@ class DoctorRepo {
    };
    static deleteToken(token, handler) {
        imRepo.execQuery({
        imDb.execQuery({
            "sql": "DELETE FROM user WHERE token=?",
            "args": [token],
            "handler": handler
@ -72,7 +67,7 @@ class DoctorRepo {
    };
    static updateStatus(userId, status, handler) {
        imRepo.execQuery({
        imDb.execQuery({
            "sql": "UPDATE user SET status=? WHERE user_id=?",
            "args": [status, userId],
            "handler": handler

src/server/repository/group.msg.repo.js → src/server/repository/mysql/group.msg.repo.js


src/server/repository/group.repo.js → src/server/repository/mysql/group.repo.js


src/server/repository/notify.msg.repo.js → src/server/repository/mysql/notify.msg.repo.js


+ 41 - 0
src/server/repository/mysql/patient.repo.js

@ -0,0 +1,41 @@
/**
 * 患者库。
 *
 * author: Sand
 * since: 2016/11/18
 */
"use strict";
var imDb = require('./db/im.db');
class Patient {
    constructor() {
    }
    findOne(patientId){
    }
    getPatientOpenid(code, handler) {
        var sql = "select openid from patients where code = ? ";
        imDb.execQuery({
            "sql": sql,
            "args": [code],
            "handler": handler
        });
    }
    // TODO: 不能直接访问三师库
    getPatientDoctorConsult(patient, doctor, handler) {
        var sql = "select * from wlyy_consult_team where patient = ? and doctor = ? and status = 0 and del = '1' ";
        imDb.execQuery({
            "sql": sql,
            "args": [patient, doctor],
            "handler": handler
        });
    };
}
module.exports = Patient;

src/server/repository/private.msg.repo.js → src/server/repository/mysql/private.msg.repo.js


src/server/repository/search.repo.js → src/server/repository/mysql/search.repo.js


src/server/repository/stats.msg.repo.js → src/server/repository/mysql/stats.msg.repo.js


src/server/repository/sync.log.js → src/server/repository/mysql/sync.log.js


src/server/repository/system.msg.repo.js → src/server/repository/mysql/system.msg.repo.js


src/server/repository/wechat.token.repo.js → src/server/repository/mysql/wechat.token.repo.js


+ 0 - 16
src/server/repository/mysql/wlyy.db.js

@ -1,16 +0,0 @@
"use strict";
var configFile = require('../../include/commons').CONFIG_FILE;
var config = require('../../resources/config/' + configFile);
var mysql = require('mysql');
var dbUtil = require('../../util/dbUtil');
var pool = mysql.createPool(config.wlyyDbConfig);
/**
 * 执行查询
 */
exports.execQuery = function(options) {
	dbUtil.execQuery(pool, options);
};

+ 0 - 39
src/server/repository/patient.repo.js

@ -1,39 +0,0 @@
/**
 * 患者数据。
 *
 * author: Sand
 * since: 2016/11/18
 */
"use strict";
var wlyyDb = require('./mysql/wlyy.db');
exports.isPatientCode = function (code, handler) {
    var sql = "select count(*) c from wlyy_patient where code = '" + code + "'";
    wlyyDb.execQuery({
        "sql": sql,
        "args": [],
        "handler": handler
    });
};
exports.getPatientOpenid = function (code, handler) {
    var sql = "select openid from wlyy_patient where code = ? ";
    wlyyDb.execQuery({
        "sql": sql,
        "args": [code],
        "handler": handler
    });
};
exports.getPatientDoctorConsult = function (patient, doctor, handler) {
    var sql = "select * from wlyy_consult_team where patient = ? and doctor = ? and status = 0 and del = '1' ";
    wlyyDb.execQuery({
        "sql": sql,
        "args": [patient, doctor],
        "handler": handler
    });
};

+ 9 - 22
src/server/repository/redis/redis.client.js

@ -1,18 +1,26 @@
/**
 * Redis客户端封装。
 *
 * 注意Redis使用Promises保证调用流程。
 *
 * https://github.com/NodeRedis/node_redis
 *
 * author: linzhuo
 * since: 2016/12/09
 */
"use strict";
let redis = require('redis');
let bluebird = require('bluebird');
let configFile = require('../../include/commons').CONFIG_FILE;
let config = require('../../resources/config/' + configFile);
let log = require("../../util/log.js");
let redisClient = null;
// 启用promises
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
class RedisClient {
    constructor() {
        this._connection = redis.createClient(
@ -39,27 +47,6 @@ class RedisClient {
        return redisClient;
    }
    //--------------------Redis快捷操作简易封装--------------------------//
    /**
     * 字符串。
     *
     * @param key
     * @param value
     * @param handler
     */
    setString(key, value, handler) {
        this._connection.set(key, value, function (err, res) {
            handler(err, res);
        })
    }
    getString(key, handler) {
        this._connection.get(key, function (err, res) {
            handler(err, res);
        })
    }
}
module.exports = RedisClient;

+ 0 - 29
src/server/repository/wlyy/wlyy.user.repo.js

@ -1,29 +0,0 @@
/**
 * 家庭医生平台-用户,包含医生与患者。
 */
"use strict";
var log = require('../../util/log');
var wlyyRepo = require("./../mysql/wlyy.db.js");
class WlyyDoctorRepo{
    constructor(){
    }
    /**
     * 获取指定时间之后更新的医生数据。
     *
     * @param timestamp
     */
    static getUpdatedUsers(timestamp, handler){
        wlyyRepo.execQuery({
            "sql": "SELECT code, name, sex, birthday, photo, level, 'doctor' 'type' FROM wlyy.wlyy_doctor d where d.czrq > ? UNION " +
            "SELECT code, name, sex, birthday, photo, '', 'patient' 'type' FROM wlyy.wlyy_patient p where p.czrq > ?",
            "args": [timestamp, timestamp],
            "handler": handler
        });
    }
}
module.exports = WlyyDoctorRepo;

+ 0 - 4
src/server/resources/schema/ichat_import_users.1.2.8.sql

@ -1,4 +0,0 @@
insert into doctors(id, name, sex, birthdate, avatar, level, locked) select code, name, sex, birthday, photo, level, 0 from wlyy.wlyy_doctor;
insert into patients(id, name, sex, birthdate, avatar) select distinct code, name, sex, birthday, photo from wlyy.wlyy_patient;
insert into sync_log(event, last_sync_time, succeed, message) values('user_sync', now(), 1, 'ok');

+ 13 - 46
src/server/resources/schema/ichat_schema.1.2.8.sql

@ -17,9 +17,6 @@ DROP TABLE IF EXISTS `p2p_messages` CASCADE
DROP TABLE IF EXISTS `group_messages` CASCADE
;
DROP TABLE IF EXISTS `sync_log` CASCADE
;
DROP TABLE IF EXISTS `muc_messages` CASCADE
;
@ -29,12 +26,6 @@ DROP TABLE IF EXISTS `participants` CASCADE
DROP TABLE IF EXISTS `sessions` CASCADE
;
DROP TABLE IF EXISTS `doctors` CASCADE
;
DROP TABLE IF EXISTS `patients` CASCADE
;
/* Create Tables */
CREATE TABLE `topics`
@ -52,7 +43,7 @@ CREATE TABLE `topics`
CREATE TABLE `p2p_messages`
(
	`id` INTEGER NOT NULL COMMENT '消息ID',
	`id` VARCHAR(32) NOT NULL COMMENT '消息ID',
	`session_id` VARCHAR(50) NOT NULL COMMENT '所属会话',
	`sender_id` VARCHAR(50) NOT NULL COMMENT '消息发送者',
	`content_type` INTEGER NOT NULL COMMENT '消息类型,1文本,2图片,3语音,4文章,5跳转,6咨询开始,7咨询结束',
@ -64,7 +55,7 @@ CREATE TABLE `p2p_messages`
CREATE TABLE `group_messages`
(
	`id` INTEGER NOT NULL COMMENT '消息ID',
	`id` VARCHAR(32) NOT NULL COMMENT '消息ID',
	`session_id` VARCHAR(50) NOT NULL COMMENT '所属会话',
	`sender_id` VARCHAR(50) NOT NULL COMMENT '消息发送者',
	`content_type` INTEGER NOT NULL COMMENT '消息类型,1文本,2图片,3语音,4文章,5跳转,6咨询开始,7咨询结束',
@ -74,18 +65,9 @@ CREATE TABLE `group_messages`
) COMMENT='群会话消息'
;
CREATE TABLE `sync_log`
(
	`event` VARCHAR(50) NOT NULL COMMENT '事件名称',
	`last_sync_time` TIMESTAMP NOT NULL COMMENT '最近更新时间',
	`succeed` TINYINT COMMENT '是否成功',
	`message` VARCHAR(50) COMMENT '消息'
) COMMENT='用户同步日志'
;
CREATE TABLE `muc_messages`
(
	`id` INTEGER NOT NULL COMMENT '消息ID',
	`id` VARCHAR(32) NOT NULL COMMENT '消息ID',
	`session_id` VARCHAR(50) NOT NULL COMMENT '所属会话',
	`sender_id` VARCHAR(50) NOT NULL COMMENT '消息发送者',
	`content_type` INTEGER NOT NULL COMMENT '消息类型,1文本,2图片,3语音,4文章,5跳转,6咨询开始,7咨询结束',
@ -115,30 +97,6 @@ CREATE TABLE `sessions`
) COMMENT='会话'
;
CREATE TABLE `doctors`
(
	`id` VARCHAR(50) NOT NULL COMMENT 'ID',
	`name` VARCHAR(30) NOT NULL COMMENT '姓名',
	`sex` INTEGER NOT NULL COMMENT '性别',
	`birthdate` DATE COMMENT '出生日期',
	`avatar` VARCHAR(255) COMMENT '头像',
	`level` INTEGER COMMENT '级别',
	`locked` TINYINT NOT NULL DEFAULT 0 COMMENT '是否禁用',
	CONSTRAINT `PK_doctors` PRIMARY KEY (`id`)
) COMMENT='医生'
;
CREATE TABLE `patients`
(
	`id` VARCHAR(50) NOT NULL COMMENT 'ID',
	`name` VARCHAR(30) COMMENT '姓名',
	`sex` INTEGER COMMENT '性别',
	`avatar` VARCHAR(255) COMMENT '头像',
	`birthdate` DATE COMMENT '出生日期',
	CONSTRAINT `PK_users` PRIMARY KEY (`id`)
) COMMENT='患者'
;
/* Create Primary Keys, Indexes, Uniques, Checks */
ALTER TABLE `topics` 
@ -169,4 +127,13 @@ ALTER TABLE `muc_messages`
 ADD INDEX `IXFK_messages_sessions` (`session_id` ASC)
;
SET FOREIGN_KEY_CHECKS=1
SET FOREIGN_KEY_CHECKS=1;
/* 用户视图:医生与患者 */
create or replace view doctors as 
select code, name, sex, birthday birthdate, photo avatar, level
from wlyy.wlyy_doctor;
create or replace view patients as 
select code, name, sex, birthday birthdate, photo avatar, openid
from wlyy.wlyy_patient;

+ 1 - 1
test/server/models/patient.Test.js

@ -8,7 +8,7 @@
var assert = require('assert');
var Patient =  require('../../../src/server/models/patient');
var Patient =  require('../../../../src/server/models/user/patient');
describe('Patient class', function () {
    describe('Method: sendMessage', function () {

+ 26 - 0
test/server/models/user/user.Test.js

@ -0,0 +1,26 @@
/**
 *
 * author: Sand
 * since: 12/13/2016
 */
"use strict";
var assert = require('assert');
var Users =  require('../../../../src/server/models/user/users');
describe('Users class', function () {
    describe('isPatientId', function () {
        it('true with really patient id', function (done) {
            let users = new Users();
            assert.strictEqual(users.isPatientId('915cc456-5b1d-11e6-8344-fa163e8aee56'), true);
        });
        it('false with random id', function (done) {
            let users = new Users();
            assert.strictEqual(users.isPatientId('not-patient_id'), false);
        })
    });
});

+ 7 - 7
test/server/repository/redis/redis.client.Test.js

@ -1,18 +1,20 @@
"use strict";
var RedisClient = require('../../../../src/server/repository/redis/redis.client');
let redisClient = RedisClient.redisClient();
let redisConn = redisClient.connection;
var assert = require('assert');
describe('Redis Client', function () {
    describe('When connected successfully', function () {
        it('should ok with set/get string', function (done) {
            let redisClient = RedisClient.redisClient();
            redisClient.setString('hello', 'world', function (err, res) {
                if(err) console.error(err);
        it('should ok with set/get string async', function (done) {
            redisConn.setAsync('hello', 'world').then(function (res) {
                assert.strictEqual(res, 'OK');
            });
            redisClient.getString('hello', function (err, res) {
            redisConn.getAsync('hello').then(function (res) {
                assert.strictEqual(res, 'world');
                done();
@ -22,8 +24,6 @@ describe('Redis Client', function () {
    describe('When sadd/srem with set', function () {
        it('should ok', function (done) {
            let redisClient = RedisClient.redisClient();
            let redisConn = redisClient.connection;
            redisConn.sadd('set', 'a', 'b', 'c');
            redisConn.smembers('set', function (err, res) {