๐Ÿ“ฆ ibakaidov / cover-test-task

๐Ÿ“„ db.js ยท 47 lines
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
47const mongoose = require('mongoose')
const {host, name} = require(__dirname + '/../../config.json').db

mongoose.Promise = Promise

const models = {
  Post: mongoose.model('Post', new mongoose.Schema({
    id: Number,
    date: Date
  }))
}

class Db {

  static get instance() {
    if (this._instance == null) {
      this._instance = new Db()
    }
    return this._instance
  }

  constructor() {
    this.initDB()

  }

  initDB() {
    mongoose.connect(`mongodb://${host}/${name}`) 
  }

  addPost({ id }) {
    let post = new models.Post({ id, date: new Date })
    return post.save()
  }
  deletePost({ id }) {
    return (models.Post.find({ id }).remove())
  }

  getTodayPosts() {
    let now = new Date()
    let startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    return models.Post.find({ date: { $gte: startOfToday } })
  }

}

module.exports = Db