Skip to content

Commit

Permalink
chore: clean zod validation in database api endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
onmax authored May 16, 2024
1 parent 224857f commit 7ad74a3
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([]),

Check failure on line 9 in src/runtime/server/api/_hub/database/[command].post.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected trailing comma
})

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

Please sign in to comment.