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 } } };