@imjxsx/localdb
Version:
A lightweight MongoDB-style BSON database for Node.js
3 lines (2 loc) • 1.65 kB
JavaScript
import o from"node:path";import{isObject as c,toError as s,replacer as u,reviver as p}from"../utils/index.js";import e from"node:fs";import{BSON as a}from"bson";import{Collection as f}from"./collection.js";class D{filepath;store;timeout=null;catch;constructor(t){this.filepath=o.isAbsolute(t)?t:o.resolve(t),this.filepath.endsWith(".bson")||(this.filepath=`${this.filepath}.bson`),this.store={}}async load(){try{try{await e.promises.access(this.filepath)}catch{await this.save();return}const t=await e.promises.readFile(this.filepath),i=a.deserialize(t),r=p(i);if(!c(r))return;this.store=r}catch(t){this.catch&&this.catch(s(t))}}async save(){try{const t=u(this.store);if(!c(t))return;const i=a.serialize(t);await e.promises.writeFile(this.filepath,i)}catch(t){this.catch&&this.catch(s(t))}}collection(t){return t=t.toLowerCase(),t.endsWith("s")||(t=`${t}s`),t in this.store||(this.store[t]={}),new f(this.store[t])}collections(){return Object.keys(this.store)}async drop(){try{await e.promises.unlink(this.filepath),this.store={},this.timeout&&clearInterval(this.timeout)}catch(t){this.catch&&this.catch(s(t))}}async stats(){try{const t=await e.promises.stat(this.filepath),i=this.collections(),r=i.reduce((h,l)=>{const n=this.store[l];return h+Object.keys(n).length},0);return{name:this.name,collections:i.length,documents:r,size:t.size,filepath:this.filepath}}catch(t){return this.catch&&this.catch(s(t)),null}}get name(){return o.basename(this.filepath,".bson")}autosave(t){this.timeout===null&&(this.timeout=setInterval(async()=>{try{await this.save()}catch(i){this.catch&&this.catch(s(i))}},t))}}export{D as DB};
//# sourceMappingURL=db.js.map