Skip to content

Commit 990e028

Browse files
authored
perf: replace Object.entries/fromEntries with Object.keys for better performance (#1639)
1 parent 6d38bc1 commit 990e028

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

src/app.ts

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { dirname, isAbsolute, join } from 'node:path'
22
import { fileURLToPath } from 'node:url'
33

4-
import { App } from '@tinyhttp/app'
4+
import { App, type Request } from '@tinyhttp/app'
55
import { cors } from '@tinyhttp/cors'
66
import { Eta } from 'eta'
77
import { Low } from 'lowdb'
@@ -13,6 +13,9 @@ import { Data, isItem, Service } from './service.js'
1313
const __dirname = dirname(fileURLToPath(import.meta.url))
1414
const isProduction = process.env['NODE_ENV'] === 'production'
1515

16+
type QueryValue = Request['query'][string] | number
17+
type Query = Record<string, QueryValue>
18+
1619
export type AppOptions = {
1720
logger?: boolean
1821
static?: string[]
@@ -57,20 +60,22 @@ export function createApp(db: Low<Data>, options: AppOptions = {}) {
5760

5861
app.get('/:name', (req, res, next) => {
5962
const { name = '' } = req.params
60-
const query = Object.fromEntries(
61-
Object.entries(req.query)
62-
.map(([key, value]) => {
63-
if (
64-
['_start', '_end', '_limit', '_page', '_per_page'].includes(key) &&
65-
typeof value === 'string'
66-
) {
67-
return [key, parseInt(value)]
68-
} else {
69-
return [key, value]
70-
}
71-
})
72-
.filter(([, value]) => !Number.isNaN(value)),
73-
)
63+
const query: Query = {}
64+
65+
Object.keys(req.query).forEach((key) => {
66+
let value: QueryValue = req.query[key]
67+
68+
if (
69+
['_start', '_end', '_limit', '_page', '_per_page'].includes(key) &&
70+
typeof value === 'string'
71+
) {
72+
value = parseInt(value);
73+
}
74+
75+
if (!Number.isNaN(value)) {
76+
query[key] = value;
77+
}
78+
})
7479
res.locals['data'] = service.find(name, query)
7580
next?.()
7681
})

0 commit comments

Comments
 (0)