tricoteuses-legifrance/src/routes/section_ta/+page.server.ts

60 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-08-10 22:05:43 +02:00
import { type Audit, auditSetNullish, cleanAudit } from "@auditors/core"
2022-08-20 19:36:21 +02:00
import { error } from "@sveltejs/kit"
2022-08-10 22:05:43 +02:00
2022-10-09 08:07:05 +02:00
import { auditSearchQueryContent } from "$lib/auditors/queries"
2022-08-14 14:23:42 +02:00
import type { SectionTa } from "$lib/legal"
import { db } from "$lib/server/databases"
2022-08-10 22:05:43 +02:00
2022-08-20 19:36:21 +02:00
import type { PageServerLoad } from "./$types"
2023-01-31 16:12:09 +01:00
function auditQuery(audit: Audit, query: URLSearchParams): [unknown, unknown] {
2022-08-10 22:05:43 +02:00
if (query == null) {
return [query, null]
}
if (!(query instanceof URLSearchParams)) {
return audit.unexpectedType(query, "URLSearchParams")
}
const data: { [key: string]: unknown } = {}
for (const [key, value] of query.entries()) {
let values = data[key] as string[] | undefined
if (values === undefined) {
values = data[key] = []
}
values.push(value)
}
const errors: { [key: string]: unknown } = {}
const remainingKeys = new Set(Object.keys(data))
2022-10-09 08:07:05 +02:00
auditSearchQueryContent(audit, data, errors, remainingKeys)
2022-08-10 22:05:43 +02:00
return audit.reduceRemaining(data, errors, remainingKeys, auditSetNullish({}))
}
2022-08-20 19:36:21 +02:00
export const load: PageServerLoad = async ({ url }) => {
2022-10-09 08:07:05 +02:00
const [query, queryError] = auditQuery(cleanAudit, url.searchParams) as [
{ limit: number; offset: number; q?: string },
unknown,
]
2022-08-10 22:05:43 +02:00
if (queryError !== null) {
console.error(
`Error in ${url.pathname} query:\n${JSON.stringify(
query,
null,
2,
)}\n\nError:\n${JSON.stringify(queryError, null, 2)}`,
)
2022-08-20 19:36:21 +02:00
throw error(400, JSON.stringify(queryError, null, 2))
2022-08-10 22:05:43 +02:00
}
const { limit, offset } = query
2022-08-13 12:18:09 +02:00
const sectionTaArray = (
await db<{ data: SectionTa }[]>`
SELECT data FROM section_ta
2022-08-10 22:05:43 +02:00
OFFSET ${offset}
LIMIT ${limit}
`
).map(({ data }) => data)
2022-08-20 19:36:21 +02:00
return { section_ta: sectionTaArray }
2022-08-10 22:05:43 +02:00
}