Repository: typicode/lowdb
Branch: main
Commit: 966a3fde68b8
Files: 37
Total size: 29.4 KB
Directory structure:
gitextract_re_ccba0/
├── .commitlintrc.json
├── .eslintrc.json
├── .gitattributes
├── .github/
│ ├── FUNDING.yml
│ └── workflows/
│ └── node.js.yml
├── .gitignore
├── .husky/
│ ├── .gitignore
│ ├── commit-msg
│ └── pre-commit
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── package.json
├── src/
│ ├── adapters/
│ │ ├── Memory.test.ts
│ │ ├── Memory.ts
│ │ ├── browser/
│ │ │ ├── LocalStorage.ts
│ │ │ ├── SessionStorage.ts
│ │ │ ├── WebStorage.test.ts
│ │ │ └── WebStorage.ts
│ │ └── node/
│ │ ├── DataFile.ts
│ │ ├── JSONFile.test.ts
│ │ ├── JSONFile.ts
│ │ ├── TextFile.test.ts
│ │ └── TextFile.ts
│ ├── browser.ts
│ ├── core/
│ │ ├── Low.test.ts
│ │ └── Low.ts
│ ├── examples/
│ │ ├── README.md
│ │ ├── browser.ts
│ │ ├── cli.ts
│ │ ├── in-memory.ts
│ │ └── server.ts
│ ├── index.ts
│ ├── node.ts
│ └── presets/
│ ├── browser.ts
│ └── node.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .commitlintrc.json
================================================
{ "extends": ["@commitlint/config-conventional"] }
================================================
FILE: .eslintrc.json
================================================
{
"extends": "@typicode",
"env":{
"browser": true,
"node": true
}
}
================================================
FILE: .gitattributes
================================================
*.ts linguist-language=JavaScript
================================================
FILE: .github/FUNDING.yml
================================================
github: typicode
================================================
FILE: .github/workflows/node.js.yml
================================================
name: Node.js CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18.x, 20.x]
steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm run build --if-present
- run: npm test
================================================
FILE: .gitignore
================================================
lib
node_modules
================================================
FILE: .husky/.gitignore
================================================
_
================================================
FILE: .husky/commit-msg
================================================
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no-install commitlint --edit "$1"
================================================
FILE: .husky/pre-commit
================================================
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run lint
npm test
================================================
FILE: CONTRIBUTING.md
================================================
By contributing, you agree to release your modifications under the MIT
license (see the file LICENSE-MIT).
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2021 typicode
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# lowdb [](https://www.npmjs.org/package/lowdb) [](https://github.com/typicode/lowdb/actions/workflows/node.js.yml)
> Simple to use type-safe local JSON database 🦉
>
> If you know JavaScript, you know how to use lowdb.
Read or create `db.json`
```js
const db = await JSONFilePreset('db.json', { posts: [] })
```
Use plain JavaScript to change data
```js
const post = { id: 1, title: 'lowdb is awesome', views: 100 }
// In two steps
db.data.posts.push(post)
await db.write()
// Or in one
await db.update(({ posts }) => posts.push(post))
```
```js
// db.json
{
"posts": [
{ "id": 1, "title": "lowdb is awesome", "views": 100 }
]
}
```
In the same spirit, query using native `Array` functions:
```js
const { posts } = db.data
posts.at(0) // First post
posts.filter((post) => post.title.includes('lowdb')) // Filter by title
posts.find((post) => post.id === 1) // Find by id
posts.toSorted((a, b) => a.views - b.views) // Sort by views
```
It's that simple. `db.data` is just a JavaScript object, no magic.
## Sponsors
[Become a sponsor and have your company logo here](https://github.com/sponsors/typicode) 👉 [GitHub Sponsors](https://github.com/sponsors/typicode)
## Features
- **Lightweight**
- **Minimalist**
- **TypeScript**
- **Plain JavaScript**
- Safe atomic writes
- Hackable:
- Change storage, file format (JSON, YAML, ...) or add encryption via [adapters](#adapters)
- Extend it with lodash, ramda, ... for super powers!
- Automatically switches to fast in-memory mode during tests
## Install
```sh
npm install lowdb
```
## Usage
_Lowdb is a pure ESM package. If you're having trouble using it in your project, please [read this](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c)._
```js
import { JSONFilePreset } from 'lowdb/node'
// Read or create db.json
const defaultData = { posts: [] }
const db = await JSONFilePreset('db.json', defaultData)
// Update db.json
await db.update(({ posts }) => posts.push('hello world'))
// Alternatively you can call db.write() explicitely later
// to write to db.json
db.data.posts.push('hello world')
await db.write()
```
```js
// db.json
{
"posts": [ "hello world" ]
}
```
### TypeScript
You can use TypeScript to check your data types.
```ts
type Data = {
messages: string[]
}
const defaultData: Data = { messages: [] }
const db = await JSONPreset('db.json', defaultData)
db.data.messages.push('foo') // ✅ Success
db.data.messages.push(1) // ❌ TypeScript error
```
### Lodash
You can extend lowdb with Lodash (or other libraries). To be able to extend it, we're not using `JSONPreset` here. Instead, we're using lower components.
```ts
import { Low } from 'lowdb'
import { JSONFile } from 'lowdb/node'
import lodash from 'lodash'
type Post = {
id: number
title: string
}
type Data = {
posts: Post[]
}
// Extend Low class with a new `chain` field
class LowWithLodash extends Low {
chain: lodash.ExpChain = lodash.chain(this).get('data')
}
const defaultData: Data = {
posts: [],
}
const adapter = new JSONFile('db.json')
const db = new LowWithLodash(adapter, defaultData)
await db.read()
// Instead of db.data use db.chain to access lodash API
const post = db.chain.get('posts').find({ id: 1 }).value() // Important: value() must be called to execute chain
```
### CLI, Server, Browser and in tests usage
See [`src/examples/`](src/examples) directory.
## API
### Presets
Lowdb provides four presets for common cases.
- `JSONFilePreset(filename, defaultData)`
- `JSONFileSyncPreset(filename, defaultData)`
- `LocalStoragePreset(name, defaultData)`
- `SessionStoragePreset(name, defaultData)`
See [`src/examples/`](src/examples) directory for usage.
Lowdb is extremely flexible, if you need to extend it or modify its behavior, use the classes and adapters below instead of the presets.
### Classes
Lowdb has two classes (for asynchronous and synchronous adapters).
#### `new Low(adapter, defaultData)`
```js
import { Low } from 'lowdb'
import { JSONFile } from 'lowdb/node'
const db = new Low(new JSONFile('file.json'), {})
await db.read()
await db.write()
```
#### `new LowSync(adapterSync, defaultData)`
```js
import { LowSync } from 'lowdb'
import { JSONFileSync } from 'lowdb/node'
const db = new LowSync(new JSONFileSync('file.json'), {})
db.read()
db.write()
```
### Methods
#### `db.read()`
Calls `adapter.read()` and sets `db.data`.
**Note:** `JSONFile` and `JSONFileSync` adapters will set `db.data` to `null` if file doesn't exist.
```js
db.data // === null
db.read()
db.data // !== null
```
#### `db.write()`
Calls `adapter.write(db.data)`.
```js
db.data = { posts: [] }
db.write() // file.json will be { posts: [] }
db.data = {}
db.write() // file.json will be {}
```
#### `db.update(fn)`
Calls `fn()` then `db.write()`.
```js
db.update((data) => {
// make changes to data
// ...
})
// files.json will be updated
```
### Properties
#### `db.data`
Holds your db content. If you're using the adapters coming with lowdb, it can be any type supported by [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).
For example:
```js
db.data = 'string'
db.data = [1, 2, 3]
db.data = { key: 'value' }
```
## Adapters
### Lowdb adapters
#### `JSONFile` `JSONFileSync`
Adapters for reading and writing JSON files.
```js
import { JSONFile, JSONFileSync } from 'lowdb/node'
new Low(new JSONFile(filename), {})
new LowSync(new JSONFileSync(filename), {})
```
#### `Memory` `MemorySync`
In-memory adapters. Useful for speeding up unit tests. See [`src/examples/`](src/examples) directory.
```js
import { Memory, MemorySync } from 'lowdb'
new Low(new Memory(), {})
new LowSync(new MemorySync(), {})
```
#### `LocalStorage` `SessionStorage`
Synchronous adapter for `window.localStorage` and `window.sessionStorage`.
```js
import { LocalStorage, SessionStorage } from 'lowdb/browser'
new LowSync(new LocalStorage(name), {})
new LowSync(new SessionStorage(name), {})
```
### Utility adapters
#### `TextFile` `TextFileSync`
Adapters for reading and writing text. Useful for creating custom adapters.
#### `DataFile` `DataFileSync`
Adapters for easily supporting other data formats or adding behaviors (encrypt, compress...).
```js
import { DataFile } from 'lowdb/node'
new DataFile(filename, {
parse: YAML.parse,
stringify: YAML.stringify
})
new DataFile(filename, {
parse: (data) => { decypt(JSON.parse(data)) },
stringify: (str) => { encrypt(JSON.stringify(str)) }
})
```
### Third-party adapters
If you've published an adapter for lowdb, feel free to create a PR to add it here.
### Writing your own adapter
You may want to create an adapter to write `db.data` to YAML, XML, encrypt data, a remote storage, ...
An adapter is a simple class that just needs to expose two methods:
```js
class AsyncAdapter {
read() {
/* ... */
} // should return Promise
write(data) {
/* ... */
} // should return Promise
}
class SyncAdapter {
read() {
/* ... */
} // should return data
write(data) {
/* ... */
} // should return nothing
}
```
For example, let's say you have some async storage and want to create an adapter for it:
```js
import { Low } from 'lowdb'
import { api } from './AsyncStorage'
class CustomAsyncAdapter {
// Optional: your adapter can take arguments
constructor(args) {
// ...
}
async read() {
const data = await api.read()
return data
}
async write(data) {
await api.write(data)
}
}
const adapter = new CustomAsyncAdapter()
const db = new Low(adapter, {})
```
See [`src/adapters/`](src/adapters) for more examples.
#### Custom serialization
To create an adapter for another format than JSON, you can use `TextFile` or `TextFileSync`.
For example:
```js
import { Adapter, Low } from 'lowdb'
import { TextFile } from 'lowdb/node'
import YAML from 'yaml'
class YAMLFile {
constructor(filename) {
this.adapter = new TextFile(filename)
}
async read() {
const data = await this.adapter.read()
if (data === null) {
return null
} else {
return YAML.parse(data)
}
}
write(obj) {
return this.adapter.write(YAML.stringify(obj))
}
}
const adapter = new YAMLFile('file.yaml')
const db = new Low(adapter, {})
```
## Limits
Lowdb doesn't support Node's cluster module.
If you have large JavaScript objects (`~10-100MB`) you may hit some performance issues. This is because whenever you call `db.write`, the whole `db.data` is serialized using `JSON.stringify` and written to storage.
Depending on your use case, this can be fine or not. It can be mitigated by doing batch operations and calling `db.write` only when you need it.
If you plan to scale, it's highly recommended to use databases like PostgreSQL or MongoDB instead.
================================================
FILE: package.json
================================================
{
"name": "lowdb",
"version": "7.0.1",
"description": "Tiny local JSON database for Node, Electron and the browser",
"keywords": [
"database",
"db",
"electron",
"embed",
"embedded",
"flat",
"JSON",
"local",
"localStorage",
"sessionStorage",
"browser",
"esm"
],
"homepage": "https://github.com/typicode/lowdb#readme",
"bugs": {
"url": "https://github.com/typicode/lowdb/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/typicode/lowdb.git"
},
"funding": "https://github.com/sponsors/typicode",
"license": "MIT",
"author": "Typicode ",
"type": "module",
"exports": {
".": "./lib/index.js",
"./node": "./lib/node.js",
"./browser": "./lib/browser.js"
},
"types": "./lib",
"typesVersions": {
"*": {
"node": [
"lib/node.d.ts"
],
"browser": [
"lib/browser.d.ts"
]
}
},
"files": [
"lib",
"!lib/examples/**/*",
"!lib/**/*.test.*"
],
"scripts": {
"test": "node --import tsx/esm --test src/**/*.test.ts src/**/**/*.test.ts",
"lint": "eslint src --ext .ts --ignore-path .gitignore",
"build": "del-cli lib && tsc",
"prepublishOnly": "npm run build",
"postversion": "git push --follow-tags && npm publish",
"prepare": "husky install"
},
"dependencies": {
"steno": "^4.0.2"
},
"devDependencies": {
"@commitlint/cli": "^18.4.3",
"@commitlint/config-conventional": "^18.4.3",
"@commitlint/prompt-cli": "^18.4.3",
"@sindresorhus/tsconfig": "^5.0.0",
"@types/express": "^4.17.21",
"@types/lodash": "^4.14.202",
"@types/node": "^20.10.5",
"@typicode/eslint-config": "^1.2.0",
"del-cli": "^5.1.0",
"eslint": "^8.56.0",
"express-async-handler": "^1.2.0",
"husky": "^8.0.3",
"lodash": "^4.17.21",
"tempy": "^3.1.0",
"ts-node": "^10.9.2",
"tsx": "^4.7.0",
"typescript": "^5.3.3"
},
"engines": {
"node": ">=18"
}
}
================================================
FILE: src/adapters/Memory.test.ts
================================================
import { deepEqual, equal } from 'node:assert/strict'
import test from 'node:test'
import { Memory, MemorySync } from './Memory.js'
await test('Memory', async () => {
const obj = { a: 1 }
const memory = new Memory()
// Null by default
equal(await memory.read(), null)
// Write
equal(await memory.write(obj), undefined)
// Read
deepEqual(await memory.read(), obj)
})
await test('MemorySync', () => {
const obj = { a: 1 }
const memory = new MemorySync()
// Null by default
equal(memory.read(), null)
// Write
equal(memory.write(obj), undefined)
// Read
deepEqual(memory.read(), obj)
})
================================================
FILE: src/adapters/Memory.ts
================================================
import { Adapter, SyncAdapter } from '../core/Low.js'
export class Memory implements Adapter {
#data: T | null = null
read(): Promise {
return Promise.resolve(this.#data)
}
write(obj: T): Promise {
this.#data = obj
return Promise.resolve()
}
}
export class MemorySync implements SyncAdapter {
#data: T | null = null
read(): T | null {
return this.#data || null
}
write(obj: T): void {
this.#data = obj
}
}
================================================
FILE: src/adapters/browser/LocalStorage.ts
================================================
import { WebStorage } from './WebStorage.js'
export class LocalStorage extends WebStorage {
constructor(key: string) {
super(key, localStorage)
}
}
================================================
FILE: src/adapters/browser/SessionStorage.ts
================================================
import { WebStorage } from './WebStorage.js'
export class SessionStorage extends WebStorage {
constructor(key: string) {
super(key, sessionStorage)
}
}
================================================
FILE: src/adapters/browser/WebStorage.test.ts
================================================
import { deepEqual, equal } from 'node:assert/strict'
import test from 'node:test'
import { WebStorage } from './WebStorage.js'
const storage: { [key: string]: string } = {}
// Mock localStorage
const mockStorage = () => ({
getItem: (key: string): string | null => storage[key] || null,
setItem: (key: string, data: string) => (storage[key] = data),
length: 1,
removeItem() {
return
},
clear() {
return
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
key(_: number): string {
return ''
},
})
global.localStorage = mockStorage()
global.sessionStorage = mockStorage()
await test('localStorage', () => {
const obj = { a: 1 }
const storage = new WebStorage('key', localStorage)
// Write
equal(storage.write(obj), undefined)
// Read
deepEqual(storage.read(), obj)
})
await test('sessionStorage', () => {
const obj = { a: 1 }
const storage = new WebStorage('key', sessionStorage)
// Write
equal(storage.write(obj), undefined)
// Read
deepEqual(storage.read(), obj)
})
================================================
FILE: src/adapters/browser/WebStorage.ts
================================================
import { SyncAdapter } from '../../core/Low.js'
export class WebStorage implements SyncAdapter {
#key: string
#storage: Storage
constructor(key: string, storage: Storage) {
this.#key = key
this.#storage = storage
}
read(): T | null {
const value = this.#storage.getItem(this.#key)
if (value === null) {
return null
}
return JSON.parse(value) as T
}
write(obj: T): void {
this.#storage.setItem(this.#key, JSON.stringify(obj))
}
}
================================================
FILE: src/adapters/node/DataFile.ts
================================================
import { PathLike } from 'fs'
import { Adapter, SyncAdapter } from '../../core/Low.js'
import { TextFile, TextFileSync } from './TextFile.js'
export class DataFile implements Adapter {
#adapter: TextFile
#parse: (str: string) => T
#stringify: (data: T) => string
constructor(
filename: PathLike,
{
parse,
stringify,
}: {
parse: (str: string) => T
stringify: (data: T) => string
},
) {
this.#adapter = new TextFile(filename)
this.#parse = parse
this.#stringify = stringify
}
async read(): Promise {
const data = await this.#adapter.read()
if (data === null) {
return null
} else {
return this.#parse(data)
}
}
write(obj: T): Promise {
return this.#adapter.write(this.#stringify(obj))
}
}
export class DataFileSync implements SyncAdapter {
#adapter: TextFileSync
#parse: (str: string) => T
#stringify: (data: T) => string
constructor(
filename: PathLike,
{
parse,
stringify,
}: {
parse: (str: string) => T
stringify: (data: T) => string
},
) {
this.#adapter = new TextFileSync(filename)
this.#parse = parse
this.#stringify = stringify
}
read(): T | null {
const data = this.#adapter.read()
if (data === null) {
return null
} else {
return this.#parse(data)
}
}
write(obj: T): void {
this.#adapter.write(this.#stringify(obj))
}
}
================================================
FILE: src/adapters/node/JSONFile.test.ts
================================================
import { deepEqual, equal } from 'node:assert/strict'
import test from 'node:test'
import { temporaryFile } from 'tempy'
import { JSONFile, JSONFileSync } from './JSONFile.js'
type Data = {
a: number
}
await test('JSONFile', async () => {
const obj = { a: 1 }
const file = new JSONFile(temporaryFile())
// Null if file doesn't exist
equal(await file.read(), null)
// Write
equal(await file.write(obj), undefined)
// Read
deepEqual(await file.read(), obj)
})
await test('JSONFileSync', () => {
const obj = { a: 1 }
const file = new JSONFileSync(temporaryFile())
// Null if file doesn't exist
equal(file.read(), null)
// Write
equal(file.write(obj), undefined)
// Read
deepEqual(file.read(), obj)
})
================================================
FILE: src/adapters/node/JSONFile.ts
================================================
import { PathLike } from 'fs'
import { DataFile, DataFileSync } from './DataFile.js'
export class JSONFile extends DataFile {
constructor(filename: PathLike) {
super(filename, {
parse: JSON.parse,
stringify: (data: T) => JSON.stringify(data, null, 2),
})
}
}
export class JSONFileSync extends DataFileSync {
constructor(filename: PathLike) {
super(filename, {
parse: JSON.parse,
stringify: (data: T) => JSON.stringify(data, null, 2),
})
}
}
================================================
FILE: src/adapters/node/TextFile.test.ts
================================================
import { deepEqual, equal } from 'node:assert/strict'
import test from 'node:test'
import { temporaryFile } from 'tempy'
import { TextFile, TextFileSync } from './TextFile.js'
await test('TextFile', async () => {
const str = 'foo'
const file = new TextFile(temporaryFile())
// Null if file doesn't exist
equal(await file.read(), null)
// Write
equal(await file.write(str), undefined)
// Read
deepEqual(await file.read(), str)
})
await test('TextFileSync', () => {
const str = 'foo'
const file = new TextFileSync(temporaryFile())
// Null if file doesn't exist
equal(file.read(), null)
// Write
equal(file.write(str), undefined)
// Read
deepEqual(file.read(), str)
})
await test('RaceCondition', async () => {
const file = new TextFile(temporaryFile())
const promises: Promise[] = []
let i = 0
for (; i <= 100; i++) {
promises.push(file.write(String(i)))
}
await Promise.all(promises)
equal(await file.read(), String(i - 1))
})
================================================
FILE: src/adapters/node/TextFile.ts
================================================
import { PathLike, readFileSync, renameSync, writeFileSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { Writer } from 'steno'
import { Adapter, SyncAdapter } from '../../core/Low.js'
export class TextFile implements Adapter {
#filename: PathLike
#writer: Writer
constructor(filename: PathLike) {
this.#filename = filename
this.#writer = new Writer(filename)
}
async read(): Promise {
let data
try {
data = await readFile(this.#filename, 'utf-8')
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ENOENT') {
return null
}
throw e
}
return data
}
write(str: string): Promise {
return this.#writer.write(str)
}
}
export class TextFileSync implements SyncAdapter {
#tempFilename: PathLike
#filename: PathLike
constructor(filename: PathLike) {
this.#filename = filename
const f = filename.toString()
this.#tempFilename = path.join(path.dirname(f), `.${path.basename(f)}.tmp`)
}
read(): string | null {
let data
try {
data = readFileSync(this.#filename, 'utf-8')
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ENOENT') {
return null
}
throw e
}
return data
}
write(str: string): void {
writeFileSync(this.#tempFilename, str)
renameSync(this.#tempFilename, this.#filename)
}
}
================================================
FILE: src/browser.ts
================================================
export * from './adapters/browser/LocalStorage.js'
export * from './adapters/browser/SessionStorage.js'
export * from './presets/browser.js'
================================================
FILE: src/core/Low.test.ts
================================================
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { deepEqual, equal, throws } from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
import lodash from 'lodash'
import { temporaryFile } from 'tempy'
import { Memory } from '../adapters/Memory.js'
import { JSONFile, JSONFileSync } from '../adapters/node/JSONFile.js'
import { Low, LowSync } from './Low.js'
type Data = {
a?: number
b?: number
}
function createJSONFile(obj: unknown): string {
const file = temporaryFile()
fs.writeFileSync(file, JSON.stringify(obj))
return file
}
function readJSONFile(file: string): unknown {
return JSON.parse(fs.readFileSync(file).toString())
}
await test('CheckArgs', () => {
const adapter = new Memory()
// Ignoring TypeScript error and pass incorrect argument
// @ts-ignore
throws(() => new Low())
// @ts-ignore
throws(() => new LowSync())
// @ts-ignore
throws(() => new Low(adapter))
// @ts-ignore
throws(() => new LowSync(adapter))
})
await test('Low', async () => {
// Create JSON file
const obj = { a: 1 }
const file = createJSONFile(obj)
// Init
const defaultData: Data = {}
const adapter = new JSONFile(file)
const low = new Low(adapter, defaultData)
await low.read()
// Data should equal file content
deepEqual(low.data, obj)
// Write new data
const newObj = { b: 2 }
low.data = newObj
await low.write()
// File content should equal new data
deepEqual(readJSONFile(file), newObj)
// Write using update()
await low.update((data) => {
data.b = 3
})
deepEqual(readJSONFile(file), { b: 3 })
})
await test('LowSync', () => {
// Create JSON file
const obj = { a: 1 }
const file = createJSONFile(obj)
// Init
const defaultData: Data = {}
const adapter = new JSONFileSync(file)
const low = new LowSync(adapter, defaultData)
low.read()
// Data should equal file content
deepEqual(low.data, obj)
// Write new data
const newObj = { b: 2 }
low.data = newObj
low.write()
// File content should equal new data
deepEqual(readJSONFile(file), newObj)
// Write using update()
low.update((data) => {
data.b = 3
})
deepEqual(readJSONFile(file), { b: 3 })
})
await test('Lodash', async () => {
// Extend with lodash
class LowWithLodash extends Low {
chain: lodash.ExpChain = lodash.chain(this).get('data')
}
// Create JSON file
const obj = { todos: ['foo', 'bar'] }
const file = createJSONFile(obj)
// Init
const defaultData = { todos: [] }
const adapter = new JSONFile(file)
const low = new LowWithLodash(adapter, defaultData)
await low.read()
// Use lodash
const firstTodo = low.chain.get('todos').first().value()
equal(firstTodo, 'foo')
})
================================================
FILE: src/core/Low.ts
================================================
export interface Adapter {
read: () => Promise
write: (data: T) => Promise
}
export interface SyncAdapter {
read: () => T | null
write: (data: T) => void
}
function checkArgs(adapter: unknown, defaultData: unknown) {
if (adapter === undefined) throw new Error('lowdb: missing adapter')
if (defaultData === undefined) throw new Error('lowdb: missing default data')
}
export class Low {
adapter: Adapter
data: T
constructor(adapter: Adapter, defaultData: T) {
checkArgs(adapter, defaultData)
this.adapter = adapter
this.data = defaultData
}
async read(): Promise {
const data = await this.adapter.read()
if (data) this.data = data
}
async write(): Promise {
if (this.data) await this.adapter.write(this.data)
}
async update(fn: (data: T) => unknown): Promise {
fn(this.data)
await this.write()
}
}
export class LowSync {
adapter: SyncAdapter
data: T
constructor(adapter: SyncAdapter, defaultData: T) {
checkArgs(adapter, defaultData)
this.adapter = adapter
this.data = defaultData
}
read(): void {
const data = this.adapter.read()
if (data) this.data = data
}
write(): void {
if (this.data) this.adapter.write(this.data)
}
update(fn: (data: T) => unknown): void {
fn(this.data)
this.write()
}
}
================================================
FILE: src/examples/README.md
================================================
# Examples
- [cli.ts](./cli.ts) - Simple CLI using JSONFileSync adapter
- [server.ts](./server.ts) - Express example using JSONFile adapter
- [browser.ts](./browser.ts) - LocalStorage adapter example
- [in-memory.ts](./in-memory.ts) - Example showing how to use in-memory adapter to write fast tests
================================================
FILE: src/examples/browser.ts
================================================
import { LocalStoragePreset } from '../presets/browser.js'
type Data = {
messages: string[]
}
const defaultData: Data = { messages: [] }
const db = LocalStoragePreset('db', defaultData)
db.update(({ messages }) => messages.push('foo'))
================================================
FILE: src/examples/cli.ts
================================================
import { JSONFileSyncPreset } from '../presets/node.js'
type Data = {
messages: string[]
}
const message = process.argv[2] || ''
const defaultData: Data = { messages: [] }
const db = JSONFileSyncPreset('file.json', defaultData)
db.update(({ messages }) => messages.push(message))
================================================
FILE: src/examples/in-memory.ts
================================================
// With this adapter, calling `db.write()` will do nothing.
// One use case for this adapter can be for tests.
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
const defaultData: Data = {}
const adapter: SyncAdapter =
process.env.NODE_ENV === 'test'
? new MemorySync()
: new JSONFileSync('db.json')
const db = new LowSync(adapter, defaultData)
db.read()
// Rest of your code...
================================================
FILE: src/examples/server.ts
================================================
// Note: if you're developing a local server and don't expect to get concurrent requests,
// it can be easier to use `JSONFileSync` adapter.
// But if you need to avoid blocking requests, you can do so by using `JSONFile` adapter.
import express from 'express'
import asyncHandler from 'express-async-handler'
import { JSONFilePreset } from '../presets/node.js'
const app = express()
app.use(express.json())
type Post = {
id: string
body: string
}
type Data = {
posts: Post[]
}
const defaultData: Data = { posts: [] }
const db = await JSONFilePreset('db.json', defaultData)
// db.data can be destructured to avoid typing `db.data` everywhere
const { posts } = db.data
app.get('/posts/:id', (req, res) => {
const post = posts.find((p) => p.id === req.params.id)
res.send(post)
})
app.post(
'/posts',
asyncHandler(async (req, res) => {
const post = req.body as Post
post.id = String(posts.length + 1)
await db.update(({ posts }) => posts.push(post))
res.send(post)
}),
)
app.listen(3000, () => {
console.log('listening on port 3000')
})
================================================
FILE: src/index.ts
================================================
export * from './adapters/Memory.js'
export * from './core/Low.js'
================================================
FILE: src/node.ts
================================================
export * from './adapters/node/DataFile.js'
export * from './adapters/node/JSONFile.js'
export * from './adapters/node/TextFile.js'
export * from './presets/node.js'
================================================
FILE: src/presets/browser.ts
================================================
import { LocalStorage } from '../adapters/browser/LocalStorage.js'
import { SessionStorage } from '../adapters/browser/SessionStorage.js'
import { LowSync } from '../index.js'
export function LocalStoragePreset(
key: string,
defaultData: Data,
): LowSync {
const adapter = new LocalStorage(key)
const db = new LowSync(adapter, defaultData)
db.read()
return db
}
export function SessionStoragePreset(
key: string,
defaultData: Data,
): LowSync {
const adapter = new SessionStorage(key)
const db = new LowSync(adapter, defaultData)
db.read()
return db
}
================================================
FILE: src/presets/node.ts
================================================
import { PathLike } from 'node:fs'
import { Memory, MemorySync } from '../adapters/Memory.js'
import { JSONFile, JSONFileSync } from '../adapters/node/JSONFile.js'
import { Low, LowSync } from '../core/Low.js'
export async function JSONFilePreset(
filename: PathLike,
defaultData: Data,
): Promise> {
const adapter =
process.env.NODE_ENV === 'test'
? new Memory()
: new JSONFile(filename)
const db = new Low(adapter, defaultData)
await db.read()
return db
}
export function JSONFileSyncPreset(
filename: PathLike,
defaultData: Data,
): LowSync {
const adapter =
process.env.NODE_ENV === 'test'
? new MemorySync()
: new JSONFileSync(filename)
const db = new LowSync(adapter, defaultData)
db.read()
return db
}
================================================
FILE: tsconfig.json
================================================
{
"extends": "@sindresorhus/tsconfig",
"compilerOptions": {
"outDir": "./lib"
}
}