Skip to content

perf: replace Object.entries/fromEntries with Object.keys for better performance #1639

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 20 additions & 15 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { dirname, isAbsolute, join } from 'node:path'
import { fileURLToPath } from 'node:url'

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

type QueryValue = Request['query'][string] | number
type Query = Record<string, QueryValue>

export type AppOptions = {
logger?: boolean
static?: string[]
Expand Down Expand Up @@ -57,20 +60,22 @@ export function createApp(db: Low<Data>, options: AppOptions = {}) {

app.get('/:name', (req, res, next) => {
const { name = '' } = req.params
const query = Object.fromEntries(
Object.entries(req.query)
.map(([key, value]) => {
if (
['_start', '_end', '_limit', '_page', '_per_page'].includes(key) &&
typeof value === 'string'
) {
return [key, parseInt(value)]
} else {
return [key, value]
}
})
.filter(([, value]) => !Number.isNaN(value)),
)
const query: Query = {}

Object.keys(req.query).forEach((key) => {
let value: QueryValue = req.query[key]

if (
['_start', '_end', '_limit', '_page', '_per_page'].includes(key) &&
typeof value === 'string'
) {
value = parseInt(value);
}

if (!Number.isNaN(value)) {
query[key] = value;
}
})
res.locals['data'] = service.find(name, query)
next?.()
})
Expand Down