Skip to content

Commit c185b4b

Browse files
committed
docs: update adapters section
1 parent 4627ec8 commit c185b4b

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

README.md

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ Lowdb now comes with TypeScript support. You can even type `db.data` content.
9494
type Data = {
9595
posts: string[] // Expect posts to be an array of strings
9696
}
97+
const adapter = new JSONFile<Data>('db.json')
9798
const db = new Low<Data>(adapter)
9899

99100
db.data
@@ -218,13 +219,17 @@ Synchronous adapter for `window.localStorage`.
218219
new LowSync(new LocalStorage(name))
219220
```
220221

222+
#### `TextFile` `TextFileSync`
223+
224+
Adapters for reading and writing text. Useful for creating custom adapters.
225+
221226
### Third-party adapters
222227

223228
If you've published an adapter for lowdb, feel free to create a PR to add it here.
224229

225230
### Writing your own adapter
226231

227-
You may want to create an adapter to write `db.data` to YAML, XML, ... or encrypt data.
232+
You may want to create an adapter to write `db.data` to YAML, XML, encrypt data, a remote storage, ...
228233

229234
An adapter is a simple class that just needs to expose two methods:
230235

@@ -235,8 +240,8 @@ class AsyncAdapter {
235240
}
236241

237242
class SyncAdapter {
238-
read() { /* ... */ } // data
239-
write(data) { /* ... */ } // void
243+
read() { /* ... */ } // should return data
244+
write(data) { /* ... */ } // should return nothing
240245
}
241246
```
242247

@@ -267,6 +272,41 @@ const db = new Low(adapter)
267272

268273
See [`src/adapters/`](src/adapters) for more examples.
269274

275+
#### Custom serialization
276+
277+
To create an adapter for another format than JSON, you can use `TextFile` or `TextFileSync`.
278+
279+
For example:
280+
281+
```js
282+
import { Adapter, Low, TextFile } from 'Low.js'
283+
import YAML from 'yaml'
284+
285+
export class YAMLFile {
286+
private adapter
287+
288+
constructor(filename: string) {
289+
this.adapter = new TextFile(filename)
290+
}
291+
292+
async read() {
293+
const data = await this.adapter.read()
294+
if (data === null) {
295+
return null
296+
} else {
297+
return YAML.parse(data)
298+
}
299+
}
300+
301+
write(obj) {
302+
return this.adapter.write(YAML.stringify(obj))
303+
}
304+
}
305+
306+
const adapter = new YAMLFile('file.yaml')
307+
const db = new Low(adapter)
308+
```
309+
270310
## Limits
271311

272312
Lowdb doesn't support Node's cluster module.

0 commit comments

Comments
 (0)