This repository has been archived by the owner on Apr 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmensagensDAO.js
71 lines (64 loc) · 1.89 KB
/
mensagensDAO.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
65
66
67
68
69
70
71
const MongoClient = require('mongodb').MongoClient
const log = require('fancy-log')
class MensagensDAO {
constructor() {
this.msgDB = null
this.connectionUrl = process.env.MONGODB_URL,
this.nomeDB = this.connectionUrl ? this.connectionUrl.split('/').pop() : null
if (!this.connectionUrl) {
log.warn('Váriável de ambiente com o URL de conexão com o banco de dados não foi definido!\n' +
'O aplicativo funcionará normalmente, mas as mensagens não serão salvas.')
}
}
connect() {
return new Promise(async (resolve, reject) => {
if (this.connectionUrl) {
const database = await MongoClient.connect(this.connectionUrl, {
useNewUrlParser: true
})
.catch(reject)
log.info('Conectado ao banco de dados')
this.msgDB = database.db(this.nomeDB)
resolve(this.msgDB)
} else {
this.dbOffline = true
resolve({
erro: 'Não foi definido um banco de dados.',
dbOffline: true
})
}
})
}
inserirUsuario(usuario) {
if (!this.dbOffline) {
return new Promise((resolve, reject) => {
let usuariosArr = this.msgDB.collection('usuarios').find({
usuario: { $eq: usuario.usuario }
}).toArray()
.catch(reject)
if (usuariosArr[0] != undefined) {
reject('O usuário já existe.')
} else {
let result = this.msgDB.collection('usuarios').insertOne(usuario)
.catch(reject)
resolve(result)
}
})
}
}
async getMsgs() {
return await this.msgDB
.collection('mensagens')
.find()
.toArray()
}
async inserirMsg(msg) {
if (!this.dbOffline) {
return await this.msgDB.collection('mensagens').insertOne(msg)
.then(() => {
console.log('Mensagem salva no BD')
})
}
}
}
module.exports = MensagensDAO