feat: convert id to correct type

This commit is contained in:
typicode
2024-01-13 02:38:32 +01:00
parent a321b653e3
commit f0fb035be0
2 changed files with 14 additions and 15 deletions

View File

@ -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

View File

@ -113,31 +113,31 @@ 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() }
function fixItemsIds(items: Item[]) {
items.forEach((item) => {
if (typeof item['id'] === 'number') {
item['id'] = item['id'].toString()
}
if (item['id'] === undefined) {
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
}