-
Notifications
You must be signed in to change notification settings - Fork 2
/
messagesService.js
64 lines (53 loc) · 1.64 KB
/
messagesService.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const MongoLib = require('../../lib/mongo');
const { ObjectId } = require('mongodb');
const { config } = require('../../config');
const boom = require('@hapi/boom');
const MessagesModel = require('../../utils/schema/messagesSchema');
const validationModelHandler = require('../../utils/middleware/validationModelHandler');
class MessagesService {
constructor() {
this.collection = config.dbCollections.messages;
this.mongoDB = new MongoLib();
}
/**
* Create a new Message
* @param {object} message message data
* @param {string} message.patientId id of patient
* @param {string} message.messageText message
* @returns {string} created messages id
*/
async createMessages(message) {
await validationModelHandler(message, MessagesModel);
const createMessageId = await this.mongoDB.create(
this.collection,
new MessagesModel(message)
);
return createMessageId;
}
/**
* Retrieve a patient messages
* @param {string} patientId patient id
* @return {object[]} messages of patient
*/
async getMessages(patientId) {
const query = {
$and: [{ patientId: ObjectId(patientId) }, { read: false }],
};
const messages = await this.mongoDB.getAll(this.collection, query);
if (messages.length == 0) {
throw boom.notFound('Not exist new messages for this patient');
}
const messagesUpdates = messages.map((message) => ObjectId(message._id));
await this.mongoDB.updateMany(
this.collection,
{
_id: {
$in: messagesUpdates,
},
},
{ read: true }
);
return messages || [];
}
}
module.exports = MessagesService;