Skip to content

Commit

Permalink
chore: clean zod validation in database api endpoints (nuxt-hub#109)
Browse files Browse the repository at this point in the history
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
  • Loading branch information
onmax and autofix-ci[bot] authored May 22, 2024
1 parent 3cf64b4 commit 38ee73a
Showing 1 changed file with 11 additions and 18 deletions.
29 changes: 11 additions & 18 deletions src/runtime/server/api/_hub/database/[command].post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { requireNuxtHubFeature } from '../../../utils/features'

const statementValidation = z.object({
query: z.string().min(1).max(1e6).trim(),
params: z.any().array()
params: z.any().array().default([])
})

export default eventHandler(async (event) => {
Expand All @@ -20,42 +20,35 @@ export default eventHandler(async (event) => {
const db = hubDatabase()

if (command === 'exec') {
const { query } = await readValidatedBody(event, z.object({
query: z.string().min(1).max(1e6).trim()
}).parse)
const { query } = await readValidatedBody(event, statementValidation.pick({ query: true }).parse)
return db.exec(query)
}
if (command === 'dump') {
return db.dump()
}
if (command === 'first') {
const { query, params, colName } = await readValidatedBody(event, z.object({
query: z.string().min(1).max(1e6).trim(),
params: z.any().array(),
colName: z.string().optional()
}).parse)
const { query, params, colName } = await readValidatedBody(event, z.intersection(
statementValidation,
z.object({ colName: z.string().optional() })
).parse)
if (colName) {
return db.prepare(query).bind(...params).first(colName)
}
return db.prepare(query).bind(...params).first()
}

if (command === 'batch') {
const statements = await readValidatedBody(event, z.array(z.object({
query: z.string().min(1).max(1e6).trim(),
params: z.any().array()
})).parse)
const statements = await readValidatedBody(event, z.array(statementValidation).parse)
return db.batch(
statements.map(stmt => db.prepare(stmt.query).bind(...stmt.params))
)
}

if (command === 'raw') {
const { query, params, columnNames } = await readValidatedBody(event, z.object({
query: z.string().min(1).max(1e6).trim(),
params: z.any().array(),
columnNames: z.boolean().default(false)
}).parse)
const { query, params, columnNames } = await readValidatedBody(event, z.intersection(
statementValidation,
z.object({ columnNames: z.boolean().default(false) })
).parse)
// @ts-expect-error overload on columnNames
return db.prepare(query).bind(...params).raw({ columnNames })
}
Expand Down

0 comments on commit 38ee73a

Please sign in to comment.