file-db.js 1.74 KB
const nedb = require('nedb');
const path = require('path');
const db = new nedb({
    filename: path.join(__dirname, '../db/user.db'),
    autoload: true
})

const fileDb = {
    findAll() {
        return new Promise((resolve, reject) => {
            db.find({}, function (err, doc) {
                if (err) {
                    return reject(err);
                }

                return resolve(doc);
            });
        })
    },
    findOne(info) {
        return new Promise((resolve, reject) => {
            db.findOne(info, function (err, doc) {
                if (err) {
                    return reject(err);
                }

                resolve(doc);
            })
        })
    },
    insert(info) {
        return new Promise((resolve, reject) => {
            db.insert(info, function (err, doc) {
                if (err) {
                    return reject(err)
                }

                resolve(doc);
            })
        })
    },
    update(id, doc) {
        return new Promise((resolve, reject) => {
            db.update({
                _id: id
            }, {
                $set: doc
            }, {}, function (err, numAffected) {
                if (err) {
                    return reject(err);
                }

                resolve(numAffected);
            });
        })
    },
    remove(id) {
        return new Promise((resolve, reject) => {
            db.remove({
                _id: id
            }, {
                returnUpdatedDocs: true
            }, function (err, numAffected, affectedDocuments) {
                if (err) {
                    return reject(err);
                }

                resolve(affectedDocuments);
            });
        })
    }
}

module.exports = fileDb;