@oceans/cli
Version:
work for oceans
82 lines (65 loc) • 1.67 kB
JavaScript
const path = require('path')
const uuidv1 = require('uuid')
const fs = require('fs')
const { merge } = require('../common/utils')
const { PROJECT_WORK_FOLDER } = require('../config')
const Datastore = require('nedb')
class Base {
constructor (name, struct) {
const dbRootPath = path.join(PROJECT_WORK_FOLDER, 'db')
if (!fs.existsSync(dbRootPath)) {
fs.mkdirSync(dbRootPath)
}
const filePath = path.join(dbRootPath, name + '.db')
this.db = new Datastore({ filename: filePath, autoload: true })
this.struct = struct
}
insert (doc) {
return new Promise((resolve, reject) => {
const info = merge(this.struct, doc)
if (!info._id) {
info._id = uuidv1()
}
this.db.insert(info, function (err) {
if (err) {
reject(err)
return false
}
resolve(info)
})
})
}
find (query, sort, skip, limit) {
return new Promise((resolve, reject) => {
let cursor = this.db.find(query)
if (sort) {
cursor = cursor.sort(sort)
}
if (skip) {
cursor = cursor.skip(skip)
}
if (limit) {
cursor = cursor.limit(limit)
}
cursor.exec((err, docs) => {
if (err) {
reject(err)
return false
}
resolve(docs)
})
})
}
remove (query, option) {
return new Promise((resolve, reject) => {
this.db.remove(query, Object.assign({ multi: true }, option || {}), (err, numRemoved) => {
if (err) {
reject(err)
return false
}
resolve(numRemoved)
})
})
}
}
module.exports = Base