mirror of
https://github.com/typicode/json-server.git
synced 2025-07-25 03:07:46 +08:00
feat: convert id to correct type
This commit is contained in:
@ -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
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user