Skip to content
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

chore: clean zod validation in database api endpoints #109

Merged
Merged
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
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
Loading