Closed stanleyume closed 10 months ago
Is there a reason not to merge this?
Thank you for the PR. This feels to me a bit too opinionated. I think by default JSONFile behavior should be to fail if syntax is incorrect (including if db.json is an empty string).
That being said, lowdb encourages the use of custom adapter to better fit a project needs. You could reuse your change this way:
class MyJSONFile<T> implements Adapter<T> {
#adapter: TextFile
constructor(filename: string) {
this.#adapter = new TextFile(filename)
}
async read(): Promise<T | null> {
const data = await this.#adapter.read()
if (!data) {
return null
} else {
return JSON.parse(data) as T
}
}
write(obj: T): Promise<void> {
return this.#adapter.write(JSON.stringify(obj, null, 2))
}
}
// ...
const adapter = new MyJSONFile<Data>(filename)
const db = new Low<Data>(MyJSONFile, defaultData)
Currently, if the JSON file is empty, it throws a JSON parse error.
With this change, it would return the default data if the adapter returns a falsy value, which covers both non-existing files and empty files.
Falsy:
null
,undefined
,NaN
,0
,"" (empty string)
,false