Skip to content

Commit

Permalink
feat: convert id to correct type
Browse files Browse the repository at this point in the history
  • Loading branch information
typicode committed Jan 13, 2024
1 parent a321b65 commit f0fb035
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 14 deletions.
1 change: 0 additions & 1 deletion src/bin.ts
Expand Up @@ -196,7 +196,6 @@ if (process.env['NODE_ENV'] !== 'production') {
observer.onReadStart = () => {
prevEndpoints = JSON.stringify(Object.keys(db.data).sort())
}

observer.onReadEnd = (data) => {
if (data === null) {
return
Expand Down
26 changes: 13 additions & 13 deletions src/service.ts
Expand Up @@ -113,31 +113,31 @@ function randomId(): string {
return randomBytes(2).toString('hex')
}

function ensureItemsHaveIds(items: Item[]): Item[] {
return items.map((item) => {
function fixItemsIds(items: Item[]) {
items.forEach((item) => {
if (typeof item['id'] === 'number') {
item['id'] = item['id'].toString()
}
if (item['id'] === undefined) {
return { ...item, id: randomId() }
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,
}),
{},
)
function fixAllItemsIds(data: Data) {
Object.values(data).forEach((value) => {
if (Array.isArray(value)) {
fixItemsIds(value)
}
})
}

export class Service {
#db: Low<Data>

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

Expand Down

0 comments on commit f0fb035

Please sign in to comment.