-
Notifications
You must be signed in to change notification settings - Fork 5
/
+server.ts
71 lines (60 loc) · 1.91 KB
/
+server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { API, querySpread, err } from 'sveltekit-zero-api'
import { deepKeys, getProperty, setProperty } from './dot-prop'
import { getContentPage } from '$src/routes/content/content'
import { Ok } from 'sveltekit-zero-api/http'
import type { Path } from './utils'
import type { Flatten, PartialPage, ClearPage } from './flatten'
// @ts-ignore too much recursion
type path = Path<ClearPage>
export type query = {
id: string
schema: PartialPage
paths?: path | path[]
flatten?: boolean
}
export type demo = <const Q extends query>(
query: Q,
ok: (res: { body: Flatten<Q['schema']> }) => void
) => Promise<any>
export async function GET<const Q extends query>(event: API<{ query: Q }>) {
const { id, paths, schema: preSchema, flatten } = querySpread(event)
const errorResponse = err.handler(
err.test(id?.length == 11, { id: 'Must be 11 characters' }),
// @ts-ignore too much recursion
err.test(!!paths || !!preSchema, {
query: 'paths or schema should be present and typed accordingly',
})
)
if (errorResponse) {
return errorResponse('BadRequest')
}
const page = await getContentPage(id)
const schema = querySpread(event).schema ?? {}
// @ts-ignore too much recursion
const flattenedPaths = [deepKeys(schema), paths ?? []]
.flat()
.map(path =>
path
// .0. => [0]
?.replace(/\.(\d+)\./gm, '[$1].')
// .0 => [0] // end of the line
?.replace(/\.(\d+$)/gm, '[$1]')
)
.filter(path => !!path)
const outputSchema = {}
for (const path of flattenedPaths) {
try {
let value = getProperty(schema, path, undefined)
if (!value) {
value = undefined // erase unknown values
}
const apiValue = getProperty(page, path, undefined)
const lastPath = flatten
? path.split('.')?.splice(-2)?.join('.') || ''
: path
// modify by reference
setProperty(outputSchema, lastPath, apiValue)
} catch (error) {}
}
return Ok({ body: outputSchema /* as Flatten<Q['schema']> */ })
}