-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
Expand file tree
/
Copy pathnormalized-adapter.ts
More file actions
47 lines (36 loc) · 1.1 KB
/
normalized-adapter.ts
File metadata and controls
47 lines (36 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import type { Adapter } from 'lowdb'
import { randomId } from '../random-id.ts'
import type { Data, Item } from '../service.ts'
export const DEFAULT_SCHEMA_PATH = './node_modules/json-server/schema.json'
export type RawData = Record<string, Item[] | Item | string | undefined> & {
$schema?: string
}
export class NormalizedAdapter implements Adapter<Data> {
#adapter: Adapter<RawData>
constructor(adapter: Adapter<RawData>) {
this.#adapter = adapter
}
async read(): Promise<Data | null> {
const data = await this.#adapter.read()
if (data === null) {
return null
}
delete data['$schema']
for (const value of Object.values(data)) {
if (Array.isArray(value)) {
for (const item of value) {
if (typeof item['id'] === 'number') {
item['id'] = item['id'].toString()
}
if (item['id'] === undefined) {
item['id'] = randomId()
}
}
}
}
return data as Data
}
async write(data: Data): Promise<void> {
await this.#adapter.write({ ...data, $schema: DEFAULT_SCHEMA_PATH })
}
}