onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
679 stars 33 forks source link

How to use memory in lowdb #974

Open onmyway133 opened 4 months ago

onmyway133 commented 4 months ago

In lowdb 7, we can use MemorySync https://github.com/typicode/lowdb/blob/main/src/examples/in-memory.ts

import { LowSync, MemorySync, SyncAdapter } from '../index.js'
import { JSONFileSync } from '../node.js'

declare global {
  // eslint-disable-next-line @typescript-eslint/no-namespace
  namespace NodeJS {
    interface ProcessEnv {
      NODE_ENV: 'test' | 'dev' | 'prod'
    }
  }
}

type Data = Record<string, unknown>
const defaultData: Data = {}
const adapter: SyncAdapter<Data> =
  process.env.NODE_ENV === 'test'
    ? new MemorySync<Data>()
    : new JSONFileSync<Data>('db.json')

const db = new LowSync<Data>(adapter, defaultData)
db.read()