Skip to content

Commit

Permalink
feat: autofix, ensure all items have an id field
Browse files Browse the repository at this point in the history
  • Loading branch information
typicode committed Jan 7, 2024
1 parent 538cda7 commit 72fc09a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
13 changes: 12 additions & 1 deletion src/service.test.ts
Expand Up @@ -6,7 +6,7 @@ import { ParsedUrlQuery } from 'querystring'

import { Data, Item, PaginatedItems, Service } from './service.js'

const defaultData = { posts: [] }
const defaultData = { posts: [], comments: [], object: {} }
const adapter = new Memory<Data>()
const db = new Low<Data>(adapter, defaultData)
const service = new Service(db)
Expand Down Expand Up @@ -62,6 +62,17 @@ type Test = {
error?: Error
}

await test('constructor', () => {
const defaultData = { posts: [{ id: '1' }, {}], object: {} } satisfies Data
const db = new Low<Data>(adapter, defaultData)
new Service(db)
if (Array.isArray(db.data['posts'])) {
const id = db.data['posts']?.at(1)?.['id']
assert.ok(id instanceof String, 'id should be a string')
assert.ok(id.length > 0, 'id should not be empty')
}
})

await test('findById', () => {
reset()
if (!Array.isArray(db.data?.[POSTS]))
Expand Down
27 changes: 26 additions & 1 deletion src/service.ts
Expand Up @@ -105,10 +105,35 @@ function deleteDependents(db: Low<Data>, name: string, dependents: string[]) {
})
}

function randomId(): string {
return randomBytes(2).toString('hex')
}

function ensureItemsHaveIds(items: Item[]): Item[] {
return items.map((item) => {
if (item['id'] === undefined) {
return { ...item, id: randomId() }
}
return item
})
}

// Ensure all items have an id
function ensureAllItemsHaveIds(data: Data): Data {
return Object.entries(data).reduce(
(acc, [key, value]) => ({
...acc,
[key]: Array.isArray(value) ? ensureItemsHaveIds(value) : value,
}),
{},
)
}

export class Service {
#db: Low<Data>

constructor(db: Low<Data>) {
db.data = ensureAllItemsHaveIds(db.data)
this.#db = db
}

Expand Down Expand Up @@ -317,7 +342,7 @@ export class Service {
const items = this.#get(name)
if (items === undefined || !Array.isArray(items)) return

const item = { id: randomBytes(2).toString('hex'), ...data }
const item = { id: randomId(), ...data }
items.push(item)

await this.#db.write()
Expand Down

0 comments on commit 72fc09a

Please sign in to comment.