| 9 | import logger from '../utils/logger'; |
| 10 | |
| 11 | export class JSONDB<DocType extends JSONDocMeta> { |
| 12 | static DB_PATH: string = ""; |
| 13 | /** |
| 14 | * If there is too many docs in filesystem, we can use meta.json to store file metas for listing |
| 15 | */ |
| 16 | private metaDb!: Low<JSONCollectionMeta>; |
| 17 | private docs: { [id: string]: Low<DocType>} = {}; |
| 18 | private dbName: string; |
| 19 | private metaKeys: string[]; |
| 20 | updateEvent = new SlotEvent<JSONDBEvent>(); |
| 21 | |
| 22 | constructor(dbName: string, metaKeys: string[]) { |
| 23 | this.dbName = dbName; |
| 24 | this.metaKeys = metaKeys |
| 25 | } |
| 26 | |
| 27 | static serve = serve; |
| 28 | |
| 29 | /** |
| 30 | * static method to create a db instance in a async way |
| 31 | * @param dbName |
| 32 | * @returns |
| 33 | */ |
| 34 | static db = async <DocType extends JSONDocMeta>(dbName: string, metaKeys: string[]): Promise<JSONDB<DocType>> => { |
| 35 | const db = new JSONDB<DocType>(dbName, metaKeys); |
| 36 | await db.init(); |
| 37 | return db; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * define the db path |
| 42 | * @param dbPath |
| 43 | * @returns |
| 44 | */ |
| 45 | static dir = (dbPath?: string): string => { |
| 46 | if (dbPath) { |
| 47 | JSONDB.DB_PATH = dbPath; |
| 48 | fsExtra.ensureDirSync(dbPath); |
| 49 | } |
| 50 | return JSONDB.DB_PATH; |
| 51 | } |
| 52 | |
| 53 | static exist = async (name: string): Promise<boolean> => { |
| 54 | const dbPath = path.join(JSONDB.DB_PATH, name); |
| 55 | return await fsExtra.pathExists(dbPath); |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * init the db |
| 60 | */ |
| 61 | init = async () => { |
| 62 | try { |
| 63 | // Initialize existing docs |
| 64 | const docsDir = path.join(JSONDB.DB_PATH, this.dbName); |
| 65 | |
| 66 | await fsExtra.ensureDir(docsDir); |
| 67 | |
| 68 | const filePath = this.#docFilePath("meta"); |