File size: 2,179 Bytes
d8a4b7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
72
73
const mongoose = require('mongoose');
const { Schema } = mongoose;

module.exports = class mongoDB {
  constructor(url, options = { useNewUrlParser: true, useUnifiedTopology: true }) {
    this.url = url;
    this.data = this._data = this._schema = this._model = {};
    this.db = null; // Inisialisasi db sebagai null
    this.options = options;
  }

  async read() {
    // Menghubungkan ke database
    try {
      this.db = await mongoose.connect(this.url, { ...this.options });
      this.connection = mongoose.connection;

      // Mendefinisikan schema
      this._schema = new Schema({
        data: {
          type: Object,
          required: true,
          default: {}
        }
      });

      // Mencoba untuk mendefinisikan model
      try {
        this._model = mongoose.model('data', this._schema);
      } catch (error) {
        // Jika model sudah ada, ambil model yang ada
        this._model = mongoose.model('data');
      }

      // Mencari data yang ada
      this._data = await this._model.findOne({});
      if (!this._data) {
        this.data = {};
        await this.write(this.data);
        this._data = await this._model.findOne({});
      } else {
        this.data = this._data.data;
      }
      return this.data;
    } catch (error) {
      console.error('Error connecting to MongoDB:', error);
      throw error; // Melemparkan kesalahan agar dapat ditangani di tempat lain
    }
  }

  async write(data) {
    if (!data) return null; // Kembalikan null jika tidak ada data

    if (!this._data) {
      // Jika tidak ada data sebelumnya, buat dokumen baru
      const newData = new this._model({ data });
      return await newData.save();
    }

    // Jika ada data, perbarui dokumen yang ada
    try {
      const docs = await this._model.findById(this._data._id);
      if (!docs) throw new Error('Document not found');

      // Memperbarui data
      docs.data = { ...docs.data, ...data }; // Menggabungkan data lama dan baru
      return await docs.save();
    } catch (error) {
      console.error('Error writing to MongoDB:', error);
      throw error; // Melemparkan kesalahan agar dapat ditangani di tempat lain
    }
  }
};