|
| 1 | +import assert from 'node:assert/strict' |
| 2 | +import test from 'node:test' |
| 3 | + |
| 4 | +import type { Adapter } from 'lowdb' |
| 5 | + |
| 6 | +import { DEFAULT_SCHEMA_PATH, NormalizedAdapter } from './adapters/normalized-adapter.ts' |
| 7 | +import type { RawData } from './adapters/normalized-adapter.ts' |
| 8 | +import type { Data } from './service.ts' |
| 9 | + |
| 10 | +class StubAdapter implements Adapter<RawData> { |
| 11 | + #data: RawData | null |
| 12 | + |
| 13 | + constructor(data: RawData | null) { |
| 14 | + this.#data = data |
| 15 | + } |
| 16 | + |
| 17 | + async read(): Promise<RawData | null> { |
| 18 | + return this.#data === null ? null : structuredClone(this.#data) |
| 19 | + } |
| 20 | + |
| 21 | + async write(data: RawData): Promise<void> { |
| 22 | + this.#data = structuredClone(data) |
| 23 | + } |
| 24 | + |
| 25 | + get data(): RawData | null { |
| 26 | + return this.#data |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +await test('read removes $schema and normalizes ids', async () => { |
| 31 | + const adapter = new StubAdapter({ |
| 32 | + $schema: './custom/schema.json', |
| 33 | + posts: [{ id: 1 }, { title: 'missing id' }], |
| 34 | + profile: { name: 'x' }, |
| 35 | + }) |
| 36 | + |
| 37 | + const normalized = await new NormalizedAdapter(adapter).read() |
| 38 | + assert.notEqual(normalized, null) |
| 39 | + |
| 40 | + if (normalized === null) { |
| 41 | + return |
| 42 | + } |
| 43 | + |
| 44 | + assert.equal(normalized['$schema'], undefined) |
| 45 | + assert.deepEqual(normalized['profile'], { name: 'x' }) |
| 46 | + |
| 47 | + const posts = normalized['posts'] |
| 48 | + assert.ok(Array.isArray(posts)) |
| 49 | + assert.equal(posts[0]?.['id'], '1') |
| 50 | + assert.equal(typeof posts[1]?.['id'], 'string') |
| 51 | + assert.notEqual(posts[1]?.['id'], '') |
| 52 | +}) |
| 53 | + |
| 54 | +await test('write always overwrites $schema', async () => { |
| 55 | + const adapter = new StubAdapter(null) |
| 56 | + const normalizedAdapter = new NormalizedAdapter(adapter) |
| 57 | + |
| 58 | + await normalizedAdapter.write({ posts: [{ id: '1' }] } satisfies Data) |
| 59 | + |
| 60 | + const data = adapter.data |
| 61 | + assert.notEqual(data, null) |
| 62 | + assert.equal(data?.['$schema'], DEFAULT_SCHEMA_PATH) |
| 63 | +}) |
0 commit comments