박권수

feat. create Model : [DoctorInfo, PatientInfo, Feedback, Profile], doctor Api, u…

…pdate User Api, update Doctor Register, update Model : [User, Bottle]
{
"extends": "eslint:recommended",
"rules": {
"semi": ["warn", "never"],
// "semi": ["warn", "never"],
"quotes": ["warn", "single"],
"no-console": ["off"]
"no-console": ["off"],
"no-unused-vars": ["warn", { "vars": "all", "args": "after-used", "ignoreRestSiblings": false }],
"no-constant-condition" : ["off"]
},
"parserOptions": {
"ecmaVersion": 9
......
......@@ -17,6 +17,7 @@
"author": "박권수",
"license": "ISC",
"dependencies": {
"moment": "^2.29.1",
"mqtt": "^4.2.6"
}
}
......
//회원가입, 로그인 및 로그아웃에 관한 api
const User = require('../../models/user');
const Profile = require('../../models/profile');
const DoctorInfo = require('../../models/doctorInfo');
const Joi = require('joi');
const jwt = require('jsonwebtoken');
exports.register = async(ctx) => {
const { userId, password, passwordCheck } = ctx.request.body;
const {
userId,
password,
passwordCheck,
userNm,
userAge,
contact,
} = ctx.request.body;
const schema = Joi.object().keys({
userId : Joi.string().email().max(50).required(),
......@@ -25,16 +35,75 @@ exports.register = async(ctx) => {
}
const user = new User({
userId
userId,
userTypeCd : 'NORMAL',
useYn : 'Y',
});
await user.setPassword(password);
await user.save();
const profile = new Profile({
userId,
userNm,
userAge,
contact,
});
await profile.save();
ctx.status = 201;
};
exports.doctorRegister = async ctx => {
const {
userId,
password,
passwordCheck,
info,
} = ctx.request.body;
const schema = Joi.object().keys({
userId : Joi.string().email().max(50).required(),
password : Joi.string().required(),
passwordCheck : Joi.string().required(),
})
const result = schema.validate(ctx.request.body);
if(result.error || password !== passwordCheck) {
ctx.status = 400;
return;
}
const existUser = await User.findByUserId(userId);
const existDoctorInfo = await DoctorInfo.findByDoctorId(userId);
if(existUser || existDoctorInfo) {
ctx.status = 409;
return;
}
const doctor = new User({
userId,
userTypeCd : 'DOCTOR',
useYn : 'W',
});
await doctor.setPassword(password);
doctor.save();
const doctorInfo = new DoctorInfo({
doctorId : userId,
info,
useYn : 'W',
});
doctorInfo.save();
ctx.status = 201;
}
exports.login = async(ctx) => {
const { userId, password } = ctx.request.body;
......@@ -61,6 +130,11 @@ exports.login = async(ctx) => {
return;
}
if(user.useYn !== 'Y') {
ctx.status = 403;
return;
}
const token = await user.generateToken();
ctx.cookies.set('access_token', token, {
httpOnly : true,
......@@ -82,4 +156,32 @@ exports.logout = async(ctx) => {
});
ctx.status = 204;
};
exports.verifyToken = async(ctx) => {
const token = ctx.req.headers.authorization;
if(!token || !token.length) {
ctx.status = 400;
ctx.body = {
name : 'Token Not Exist',
message : 'Not Exist Token',
expiredAt : null,
};
return;
}
await jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if(err) {
ctx.status = 400;
ctx.body = err;
return;
}
});
ctx.status = 200;
ctx.body = {
name : 'Token Exist',
message : 'Token Work',
expiredAt : null,
};
};
\ No newline at end of file
......
const Router = require('koa-router');
const authCtrl = require('./auth.ctrl');
const Router = require('koa-router')
const authCtrl = require('./auth.ctrl')
const auth = new Router();
const auth = new Router()
/**
* 회원가입 (email type)
* 회원가입 (email type) : 환자 회원가입
* url : http://localhost:4000/api/auth/register
* request parameter : userId, password, passwordCheck
* return : null
*/
auth.post('/register', authCtrl.register);
auth.post('/register', authCtrl.register)
/**
* 회원가입 (email type) : 의사 회원가입
* url : http://localhost:4000/api/auth/register/doctor
* request parameter : userId, password, passwordCheck, doctorInfo
* return : null
*/
auth.post('/register/doctor', authCtrl.doctorRegister)
/**
* 로그인 (email type)
......@@ -17,7 +25,7 @@ auth.post('/register', authCtrl.register);
* request parameter : userId, password
* return : userId
*/
auth.post('/login', authCtrl.login);
auth.post('/login', authCtrl.login)
/**
* 로그아웃
......@@ -25,6 +33,14 @@ auth.post('/login', authCtrl.login);
* request parameter : null
* return : null
*/
auth.post('/logout', authCtrl.logout);
auth.post('/logout', authCtrl.logout)
/**
* 토큰이 유효한지 확인
* url : http://localhost:4000/api/auth/verifytoken
* request parameter : token(headers : authorization)
* return : result;
*/
auth.get('/verifytoken', authCtrl.verifyToken);
module.exports = auth;
\ No newline at end of file
......
......@@ -3,6 +3,7 @@ const Bottle = require('../../models/bottle');
const Hub = require('../../models/hub');
const Medicine = require('../../models/medicine');
const User = require('../../models/user');
const History = require('../../models/history');
const Mqtt = require('../../lib/MqttModule');
const jwt = require('jsonwebtoken');
......@@ -16,7 +17,7 @@ exports.bottleConnect = async(ctx) => {
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
if(!user || !user.userTypeCd || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
......@@ -70,7 +71,7 @@ exports.bottleDisconnect = async(ctx) => {
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
if(!user || !user.userTypeCd || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
......@@ -102,7 +103,7 @@ exports.bottleDisconnect = async(ctx) => {
};
//약병 정보를 조회 -> 약병에 현재 데이터를 요청한다. message : req
exports.lookupInfo = async(ctx) => {
exports.getBottleInfo = async(ctx) => {
const token = ctx.req.headers.authorization;
if(!token || !token.length) {
ctx.status = 401;
......@@ -111,36 +112,52 @@ exports.lookupInfo = async(ctx) => {
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
if(!user || !user.userTypeCd || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
const { bottleId } = ctx.params;
const isBottleExist = await Bottle.findByBottleId(bottleId);
if(!isBottleExist) {
const bottle = await Bottle.findByBottleId(bottleId);
if(!bottle) {
ctx.status = 404;
return;
}
const hub = await Hub.findByHubId(isBottleExist.getHubId());
if(hub.getHub_UserId() !== userId) {
const hub = await Hub.findByHubId(bottle.getHubId());
if(hub.getHub_UserId() !== userId || user.userTypeCd !== 'DOCTOR') {
ctx.status = 403;
return;
}
const hosting = hub.getHubHost();
//서버에서 bottle로 데이터를 요청한다.
const client = await Mqtt.mqttOn(hosting);
const topic = 'bottle/' + bottleId + '/stb';
const message = 'req';
await Mqtt.mqttPublishMessage(client, { topic, message });
if(user.userTypeCd === 'NORMAL') {
const hosting = hub.getHubHost();
//서버에서 bottle로 데이터를 요청한다.
const client = await Mqtt.mqttOn(hosting);
const topic = 'bottle/' + bottleId + '/stb';
const message = 'req';
await Mqtt.mqttPublishMessage(client, { topic, message });
const bottle = await Bottle.findByBottleId(bottleId);
ctx.status = 200;
ctx.body = bottle;
const bottle = await Bottle.findByBottleId(bottleId);
ctx.status = 200;
ctx.body = bottle;
return;
} else if (user.userTypeCd === 'DOCTOR') {
let result = {
bottle,
history : [],
};
result.historyList = History.findByBottleId(bottle.bottleId);
ctx.status = 200;
ctx.body = result;
return;
}
}
//약병의 ID를 찾아서 약의 정보를 등록 : Post
......@@ -153,7 +170,7 @@ exports.setMedicine = async(ctx) => {
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
if(!user || !user.userTypeCd || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
......@@ -199,7 +216,7 @@ exports.getBottleList = async(ctx) => {
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
if(!user || !user.userTypeCd || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
......
......@@ -25,7 +25,7 @@ bottle.delete('/:bottleId', bottleCtrl.bottleDisconnect);
* url : http://localhost:4000/api/bottle/:bottleId
* return : bottle(json type)
*/
bottle.get('/:bottleId', bottleCtrl.lookupInfo);
bottle.get('/:bottleId', bottleCtrl.getBottleInfo);
/**
* 약병에 약 등록 = 약 검색 후 약 ID(medicineId)와 복용 정보 보고 사용자가 약 복용량(dosage) 입력
......
//의사가 사용할 수 있는 Api
const User = require('../../models/user');
const Profile = require('../../models/profile');
const Bottle = require('../../models/bottle');
const Medicine = require('../../models/medicine');
const History = require('../../models/history');
const Feedback = require('../../models/feedback');
const Hub = require('../../models/hub');
const PatientInfo = require('../../models/patientInfo');
const jwt = require('jsonwebtoken');
/**
* 관리하는 환자 목록을 모두 가져옴
* @param {*} ctx
* http methods : GET
*/
exports.getPatientList = async ctx => {
const token = ctx.req.headers.authorization;
if (!token || !token.length) {
ctx.status = 401;
return;
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || user.userTypeCd !== 'DOCTOR' || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
const managePatientIdList = await PatientInfo.findAllByDoctorId(userId);
const result = managePatientIdList.map(async patientId => {
const patient = await User.findByUserId(patientId);
return patient;
});
ctx.status = 200;
ctx.body = result;
};
/**
* 관리하는 특정 환자의 정보를 가져온다.
* @param {*} ctx
* http methods : GET
*/
exports.getPatientDetail = async ctx => {
const token = ctx.req.headers.authorization;
if (!token || !token.length) {
ctx.status = 401;
return;
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || user.userTypeCd !== 'DOCTOR' || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
const { patientId } = ctx.params;
const patient = await User.findByUserId(patientId);
if(!patient || patient.useYn !== 'Y') {
ctx.status = 404;
return;
}
const isDoctorsPatient = await PatientInfo.findByPatientIdAndDoctorId(patientId, userId);
if(!isDoctorsPatient) {
ctx.status = 403;
return;
}
const profile = await Profile.findByUserId(patientId);
//reqUser의 약병 조회도 한번에
const reqUserHubList = await Hub.findAllByUserId(patientId);
const reqUserBottleList = [];
await Promise.all(reqUserHubList.map(async hub => {
const bottleList = await Bottle.findAllByHubId(hub.hubId);
reqUserBottleList.push(...bottleList);
}));
const result = {
...profile,
info : isDoctorsPatient.getInfo(),
bottleList : reqUserBottleList,
};
ctx.status = 200;
ctx.body = result;
};
/**
* 관리하는 환자의 특병 약병을 조회하여, 복용을 잘 하고 있는지 확인한다.
* @param {*} ctx
* http methods : GET
*/
exports.getBottleDetail = async ctx => {
const token = ctx.req.headers.authorization;
if (!token || !token.length) {
ctx.status = 401;
return;
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || user.userTypeCd !== 'DOCTOR' || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
const { bottleId } = ctx.params;
const bottle = await Bottle.findByBottleId(bottleId);
if(!bottle) {
ctx.status = 404;
return;
}
if(bottle.getDoctorId() !== userId) {
ctx.status = 403;
return;
}
//약병에 들어있는 약 정보와 복용 내역을 가져온다.
const bottleInfo = {
temperature : bottle.temperature,
humidity : bottle.humidity,
dosage : bottle.dosage,
balance : bottle.balance,
};
const medicine = await Medicine.findByMedicineId(bottle.getMedicineId());
const takeHistory = await History.findByBottleIdAndMedicineId(bottleId, bottle.getMedicineId());
const result = {
bottleInfo,
medicine,
takeHistory,
};
ctx.status = 200;
ctx.body = result;
};
/**
* 특정 환자의 특이사항을 기록한다.
* @param {*} ctx
* http methods : PATCH
*/
exports.writeReqPatientReport = async ctx => {
const token = ctx.req.headers.authorization;
if (!token || !token.length) {
ctx.status = 401;
return;
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || user.userTypeCd !== 'DOCTOR' || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
const { reqUserId, info } = ctx.request.body;
const patient = await User.findByUserId(reqUserId);
if(!patient || patient.useYn !== 'Y') {
ctx.status = 404;
return;
}
const patientInfo = await PatientInfo.findByPatientIdAndDoctorId(reqUserId, userId);
if(!patientInfo) {
ctx.status = 404;
return;
}
await patientInfo.updateInfo(info);
patientInfo.save();
ctx.status = 200;
};
/**
* 약을 복용중인 환자의 약병(=복용중인 약)에 대한 피드백을 등록한다.
* @param {*} ctx
* http methods : POST
*/
exports.writeReqBottleFeedback = async ctx => {
const token = ctx.req.headers.authorization;
if (!token || !token.length) {
ctx.status = 401;
return;
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || user.userTypeCd !== 'DOCTOR' || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
const { bottleId, fdbType, feedback } = ctx.request.body;
const bottle = await Bottle.findByBottleId(bottleId);
if(!bottle) {
ctx.status = 404;
return;
}
if(bottle.getDoctorId() !== userId) {
ctx.status = 403;
return;
}
const newFeedback = new Feedback({
fdbDtm : new Date(),
fdbType,
bottleId,
doctorId : userId,
feedback,
});
newFeedback.save();
ctx.status = 200;
};
/**
* 새로운 환자를 등록한다.
* @param {*} ctx
* http methods : POST
*/
exports.registerNewPatient = async ctx => {
const token = ctx.req.headers.authorization;
if (!token || !token.length) {
ctx.status = 401;
return;
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || user.userTypeCd !== 'DOCTOR') {
ctx.status = 403;
return;
}
const { reqUserId } = ctx.request.body;
const patient = await User.findByUserId(reqUserId);
if(!patient || patient.useYn !== 'Y') {
ctx.status = 404;
return;
}
const patientInfo = new PatientInfo({
patientId : reqUserId,
doctorId : userId,
info : '',
});
patientInfo.updateInfo('환자 등록');
patientInfo.save();
ctx.status = 200;
};
/**
* 등록된 환자를 해제한다.
* @param {*} ctx
* http methods : DELETE
*/
exports.removeReqPatient = async ctx => {
const token = ctx.req.headers.authorization;
if (!token || !token.length) {
ctx.status = 401;
return;
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || user.userTypeCd !== 'DOCTOR') {
ctx.status = 403;
return;
}
const { patientId } = ctx.params;
const patient = await User.findByUserId(patientId);
if(!patient || patient.useYn !== 'Y') {
ctx.status = 404;
return;
}
const patientInfo = await PatientInfo.findByPatientIdAndDoctorId(patientId, userId);
if(!patientInfo) {
ctx.status = 404;
return;
}
await PatientInfo.deleteOne({
patientId,
doctorId : userId,
});
ctx.status = 200;
};
\ No newline at end of file
const Router = require('koa-router');
const doctorCtrl = require('./doctor.ctrl');
const doctor = new Router();
/**
* 현재 로그인한 유저(의사)의 관리 환자 목록을 가져옴
* request parameter
* url : http://localhost:4000/doctor/patient
* return : patient List
*/
doctor.get('/patient', doctorCtrl.getPatientList);
/**
* 현재 로그인한 유저(의사)의 관리 환자 상세 정보를 가져옴
* request parameter : patient Id
* url : http://localhost:4000/doctor/patient/:patientId
* return : patient Detail
*/
doctor.get('/patient/:patientId', doctorCtrl.getPatientDetail);
/**
* 현재 로그인한 유저(의사)의 관리 약병 상세 정보를 가져옴
* request parameter : bottle Id
* url : http://localhost:4000/doctor/bottle/:bottleId
* return : bottle Detail
*/
doctor.get('/bottle/:bottleId', doctorCtrl.getBottleDetail);
/**
* 현재 로그인한 유저(의사)의 특정 관리 환자의 특이사항을 기록함
* request parameter : reqUserId, info
* url : http://localhost:4000/doctor/patient
* return : null
*/
doctor.patch('/patient', doctorCtrl.writeReqPatientReport);
/**
* 현재 로그인한 유저(의사)의 특정 관리 환자의 약병의 피드백을 기록함
* request parameter : bottleId, fdbType, feedback
* url : http://localhost:4000/doctor/bottle
* return : null
*/
doctor.post('/bottle', doctorCtrl.writeReqBottleFeedback);
/**
* 현재 로그인한 유저(의사)의 관리 환자를 등록함.
* request parameter : reqUserId
* url : http://localhost:4000/doctor/patient
* return : null
*/
doctor.post('/patient', doctorCtrl.registerNewPatient);
/**
* 현재 로그인한 유저(의사)의 특정 관리 환자를 삭제함.
* request parameter : patientId
* url : http://localhost:4000/doctor/patient/:patientId
* return : null
*/
doctor.delete('/patient/:patientId', doctorCtrl.removeReqPatient);
module.exports = doctor;
\ No newline at end of file
......@@ -14,7 +14,7 @@ exports.hubConnect = async (ctx) => {
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
if(!user || !user.userTypeCd || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
......@@ -55,7 +55,7 @@ exports.getHubList = async(ctx) => {
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
if(!user || !user.userTypeCd || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
......@@ -79,7 +79,7 @@ exports.hubDisconnect = async(ctx) => {
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
if(!user || !user.userTypeCd || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
......
......@@ -4,13 +4,15 @@ const user = require('./user')
const bottle = require('./bottle')
const hub = require('./hub')
const medicine = require('./medicine')
const doctor = require('./doctor');
const api = new Router()
const api = new Router();
api.use('/auth', auth.routes())
api.user('/user', user.routes())
api.use('/user', user.routes())
api.use('/bottle', bottle.routes())
api.use('/hub', hub.routes())
api.use('/medicine', medicine.routes())
api.use('/doctor', doctor.routes());
module.exports = api
\ No newline at end of file
module.exports = api;
\ No newline at end of file
......
const Router = require('koa-router')
const userCtrl = require('./user.ctrl')
const user = new Router()
const user = new Router();
/**
* 현재 유저 정보 조회
......@@ -9,21 +9,6 @@ const user = new Router()
* url : http://localhost:4000/api/user
* return : Object User
*/
user.get('/', userCtrl.myInfo)
/**
* 현재 유저의 타입에 따라 요청 유저 정보 조회(의사 : 환자, 관리자 : 모든 유저)
* request parameter : token
* url : http://localhost:4000/api/user/:reqUserId
* return : status
*/
user.get('/:reqUserId', userCtrl.getUserDetail)
/**
* 현재 유저의 타입에 따라 요청 유저 정보 수정(의사 : 환자, 관리자 : 모든 유저)
* request parameter : token
* url : http://localhost:4000/api/user/:reqUserId
* return : status
*/
user.patch('/:reqUserId', userCtrl.updateReqUser)
user.get('/', userCtrl.getMyDetail);
module.exports = user;
......
//유저에 관련된 Api
const User = require('../../models/user')
const Bottle = require('../../models/bottle')
const Hub = require('../../models/hub')
const jwt = require('jsonwebtoken')
const User = require('../../models/user');
const Profile = require('../../models/profile');
const jwt = require('jsonwebtoken');
exports.myInfo = async ctx => {
exports.getMyDetail = async ctx => {
const token = ctx.req.headers.authorization
if (!token || !token.length) {
ctx.status = 401
......@@ -14,118 +13,19 @@ exports.myInfo = async ctx => {
const { userId } = jwt.verify(token, process.env.JWT_SECRET)
const user = await User.findById(userId)
if(!user || !user.userTypeCd) {
ctx.status = 403
return
}
let result = {
myInfo : user,
myDoctor : null,
patientList : [],
userList : [],
if(!user || !user.userTypeCd || user.useYn !== 'Y') {
ctx.status = 403;
return;
}
if (user.userTypeCd === 'NORMAL') {
const doctor = await User.findById(user.doctorId)
result.myDoctor = doctor
const profile = await Profile.findByUserId(userId);
} else if (user.userTypeCd === 'DOCTOR') {
const patientList = await User.findAllByDoctorId(user.userId)
result.patientList = patientList
ctx.status = 200;
ctx.body = profile;
} else if (user.userTypeCd === 'MANAGER') {
const userList = await User.find()
result.userList = userList
}
ctx.status = 200
ctx.body = result
}
exports.getUserDetail = async ctx => {
const token = ctx.req.headers.authorization
if (!token || !token.length) {
ctx.status = 401
return
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET)
const user = await User.findById(userId)
if(!user) {
ctx.status = 403
return
} else if (user.userTypeCd === 'NORMAL') {
ctx.status = 403
return
}
let result = {
reqUser : user,
reqUserBottleList : [],
}
if (user.userTypeCd === 'DOCTOR') {
const { reqUserId } = ctx.params
const reqUser = await User.findById(reqUserId)
if (!reqUser) {
ctx.status = 404
return
}
if(reqUser.doctorId !== user.userId) {
ctx.status = 403
return
}
const reqUserHubList = await Hub.findAllByUserId(reqUserId)
if(reqUserHubList && reqUserHubList.length) {
const reqUserBottleList = []
await Promise.all(reqUserHubList.forEach(async hub => {
const bottle = await Bottle.findAllByHubId(hub.hubId)
reqUserBottleList.push(...bottle)
}))
result.reqUserBottleList = reqUserBottleList
}
}
ctx.status = 200
ctx.body = result
//toDo
exports.updateMyInfo = async ctx => {
}
exports.updateReqUser = async ctx => {
const token = ctx.req.headers.authorization
if (!token || !token.length) {
ctx.status = 401
return
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET)
const user = await User.findById(userId)
if(!user) {
ctx.status = 403
return
}
if (user.userTypeCd === 'MANAGER') {
const { useYn } = ctx.request.body
const { reqUserId } = ctx.params
const reqUser = await User.findById(reqUserId)
if(!reqUser) {
ctx.status = 404
return
}
await reqUser.setUseYn(useYn)
await reqUser.save()
return
}
ctx.status = 200
}
\ No newline at end of file
......
const Bottle = require('../models/bottle');
const History = require('../models/history');
//message subscribe 후 message를 가공한 이후 해당 데이터를 보낼 topic과 message를 리턴하는 함수
exports.dataPublish = async (topic, message) => {
......@@ -65,24 +66,28 @@ const bottleInfoUpdate = async(data) => {
humidity = parseFloat(humidity);
balance = parseInt(balance);
if(isOpen) {
await Bottle.findOneAndUpdate({
bottleId
}, { recentOpen : openDate });
}
const bottle = await Bottle.findByBottleId(bottleId);
if(balance !== -1) {
await Bottle.findOneAndUpdate({
bottleId
}, { balance })
if(bottle) {
if(isOpen) {
const history = new History({
takeDate : new Date(openDate),
bottleId,
medicineId : bottle.getMedicineId(),
});
history.save();
}
if(balance !== -1) {
await Bottle.findOneAndUpdate({
bottleId
}, { balance })
}
bottle.updateTemperature(temperature);
bottle.updateHumidity(humidity);
bottle.save();
}
await Bottle.findOneAndUpdate({
bottleId
}, {
temperature,
humidity
});
}
//해당 MQTT Broker(client)에 bottleId의 정보에 관한 topic과 message를 리턴한다.
......
......@@ -10,7 +10,7 @@ exports.updateMedicineInfo = async() => {
//queryUrl을 return하는 함수 : 한 페이지에 100개의 item씩 요청할 수 있다.
const getQueryURL = (i) => {
const url = "http://apis.data.go.kr/1471000/DrbEasyDrugInfoService/getDrbEasyDrugList";
const url = 'http://apis.data.go.kr/1471000/DrbEasyDrugInfoService/getDrbEasyDrugList';
const queryParams = '?' + encodeURIComponent('ServiceKey') + '=' + process.env.SERVICE_KEY;
const pageNum = '&' + encodeURIComponent('pageNo') + '=' + encodeURIComponent(i);
const numOfItem = '&' + encodeURIComponent('numOfRows') + '=' + encodeURIComponent(100);
......
......@@ -7,10 +7,11 @@ const BottleSchema = new Schema ({
temperature : { type : Number, default : 0 },
humidity : { type : Number, default : 0 },
balance : { type : Number, default : 0 },
medicineId : { type : Number, default : null, },
medicineId : { type : Number, },
dosage : { type : Number, default : 0 },
hubId : { type : Number, ref : 'Hub' },
})
hubId : { type : Number, required : true, },
doctorId : { type : String, default : null, },
});
BottleSchema.statics.findByBottleId = function(bottleId) {
return this.findOne({ bottleId });
......@@ -20,14 +21,14 @@ BottleSchema.statics.findAllByHubId = function(hubId) {
return this.find({ hubId });
};
BottleSchema.statics.findAllByDoctorId = function(doctorId) {
return this.find({ doctorId });
}
BottleSchema.methods.getBottleId = function() {
return this.bottleId;
};
BottleSchema.methods.getRecentOpenDate = function() {
return this.recentOpen;
};
BottleSchema.methods.getTemperature = function() {
return this.temperature;
};
......@@ -52,12 +53,24 @@ BottleSchema.methods.getHubId = function() {
return this.hubId;
};
BottleSchema.methods.getDoctorId = function() {
return this.doctorId;
};
BottleSchema.methods.setMedicineId = function(medicineId) {
this.medicineId = medicineId;
};
BottleSchema.statics.setDosage = function(dosage) {
BottleSchema.methods.setDosage = function(dosage) {
this.dosage = dosage;
};
BottleSchema.methods.updateTemperature = function (temperature) {
this.temperature = temperature;
};
BottleSchema.methods.updateHumidity = function (humidity) {
this.humidity = humidity;
};
module.exports = mongoose.model('Bottle', BottleSchema);
\ No newline at end of file
......
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const DoctorInfoSchema = new Schema({
doctorId : { type : String, required : true, },
info : {
doctorLicense : { type : String, required : true, },
hospitalNm : { type : String, default : null, },
hosptialAddr : { type : String, default : null, },
contact : { type : String, required : true, },
},
useYn : { type : String, default : 'W', required : true, },
});
DoctorInfoSchema.statics.findByDoctorId = function(doctorId) {
return this.findOne({ doctorId });
};
DoctorInfoSchema.methods.setUseYn = function(useYn) {
this.useYn = useYn;
};
module.exports = mongoose.model('DoctorInfo', DoctorInfoSchema);
\ No newline at end of file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const FeedbackSchema = new Schema({
fdbDtm : { type : Date, default : Date.now, required : true, },
fdbType : { type : String, required : true, },
bottleId : { type : Number, required : true, },
doctorId : { type : String, required : true, },
feedback : { type : String, required : true, },
});
FeedbackSchema.statics.findAllByBottleId = function(bottleId) {
return this.find({ bottleId });
};
FeedbackSchema.statics.findAllByBottleIdAndDoctorId = function(bottleId, doctorId) {
return this.find({ bottleId, doctorId });
};
module.exports = mongoose.model('Feedback', FeedbackSchema);
\ No newline at end of file
const mongoose = require('mongoose');
const moment = require('moment');
const Schema = mongoose.Schema;
const PatientInfoSchema = new Schema({
patientId : { type : String, required : true, },
doctorId : { type : String, required : true, },
info : { type : String, required : true, },
});
PatientInfoSchema.statics.findAllByPatientId = function(patientId) {
return this.find({ patientId });
};
PatientInfoSchema.statics.findAllByDoctorId = function(doctorId) {
return this.find({ doctorId });
};
PatientInfoSchema.statics.findByPatientIdAndDoctorId = function(patientId, doctorId) {
return this.findOne({ patientId, doctorId });
};
PatientInfoSchema.methods.getInfo = function() {
return this.info;
};
PatientInfoSchema.methods.updateInfo = function(info) {
const date = moment(new Date()).format('YYYY-MM-DD hh:mm');
if(this.info.length)
this.info = this.info.concat('\n\n', `${date} => ${info}`);
else
this.info = `${date} => ${info}`;
};
module.exports = mongoose.model('PatientInfo', PatientInfoSchema);
\ No newline at end of file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProfileSchema = new Schema({
userId : { type : String, required : true, },
userNm : { type : String, required : true, },
userAge : { type : Number, required : true, },
contact : { type : String, required : true, },
});
ProfileSchema.statics.findByUserId = function(userId) {
return this.findOne({ userId });
};
ProfileSchema.methods.updateUserContact = function(contact) {
this.contact = contact;
};
ProfileSchema.methods.updateUserAge = function() {
this.userAge = this.userAge + 1;
};
module.exports = mongoose.model('Profile', ProfileSchema);
\ No newline at end of file
......@@ -8,8 +8,7 @@ const UserSchema = new Schema ({
userId : { type: String, required : true, unique : true, lowercase : true },
hashedPassword : { type : String, required : true },
userTypeCd : { type : String, required : true, default : 'NORMAL' },
doctorId : { type : String, default : null },
useYn : { type : Boolean, default : true },
useYn : { type : String, default : 'W', required : true, },
});
UserSchema.methods.setPassword = async function(password) {
......@@ -30,10 +29,6 @@ UserSchema.statics.findByUserId = async function(userId) {
return this.findOne({ userId });
};
UserSchema.statics.findAllByDoctorId = async function(doctorId) {
return this.find({ doctorId });
};
UserSchema.statics.findAllByUserTypeCd = async function(userTypeCd) {
return this.find({ userTypeCd });
};
......@@ -50,4 +45,4 @@ UserSchema.methods.generateToken = function() {
return token;
};
module.exports = mongoose.model("User", UserSchema);
\ No newline at end of file
module.exports = mongoose.model('User', UserSchema);
\ No newline at end of file
......