-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapiSchemas.ts
More file actions
78 lines (66 loc) · 2.48 KB
/
apiSchemas.ts
File metadata and controls
78 lines (66 loc) · 2.48 KB
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
72
73
74
75
76
77
78
import type { RefinementCtx } from 'zod/v4'
import z from 'zod/v4'
import { decodeCursor } from './cursorCodec.ts'
export const MANDATORY_PAGINATION_CONFIG_SCHEMA = z.object({
limit: z.coerce.number().gt(0),
before: z.string().min(1).optional(),
after: z.string().min(1).optional(),
})
export type MandatoryPaginationParams = z.infer<typeof MANDATORY_PAGINATION_CONFIG_SCHEMA>
export const OPTIONAL_PAGINATION_CONFIG_SCHEMA = MANDATORY_PAGINATION_CONFIG_SCHEMA.partial({
limit: true,
})
export type OptionalPaginationParams = z.infer<typeof OPTIONAL_PAGINATION_CONFIG_SCHEMA>
export const AFTER_PAGINATION_CONFIG_SCHEMA = MANDATORY_PAGINATION_CONFIG_SCHEMA.omit({
before: true,
})
export type AfterPaginationParams = z.infer<typeof AFTER_PAGINATION_CONFIG_SCHEMA>
const decodeCursorHook = (value: string | undefined, ctx: RefinementCtx) => {
if (!value) return undefined
// Try to decode as base64 (for encoded numbers/objects)
const result = decodeCursor(value)
if (result.result) return result.result
ctx.addIssue({
message: 'Invalid cursor',
code: 'custom',
params: { message: result.error?.message },
})
}
export const encodedCursorMandatoryPaginationSchema = <
CursorType extends z.ZodSchema<unknown, Record<string, unknown> | number | undefined>,
>(
cursorType: CursorType,
) => {
const cursor = z.string().transform(decodeCursorHook).pipe(cursorType.optional()).optional()
return z.object({
limit: z.coerce.number().gt(0),
before: cursor,
after: cursor,
})
}
export const encodedCursorOptionalPaginationSchema = <
CursorType extends z.ZodSchema<unknown, Record<string, unknown> | number | undefined>,
>(
cursorType: CursorType,
) => encodedCursorMandatoryPaginationSchema(cursorType).partial({ limit: true })
export const zMeta = z.object({
count: z.number(),
cursor: z.string().optional().describe('Pagination cursor, a last item id from this result set'),
hasMore: z.boolean().describe('Whether there are more items to fetch'),
})
export type PaginationMeta = z.infer<typeof zMeta>
export const paginatedResponseSchema = <T extends z.ZodSchema>(dataSchema: T) =>
z.object({
data: z.array(dataSchema),
meta: zMeta,
})
export type PaginatedResponse<T extends Record<string, unknown>> = {
data: T[]
meta: PaginationMeta
}
export const COMMON_ERROR_RESPONSE_SCHEMA = z.object({
message: z.string(),
errorCode: z.string(),
details: z.any().optional(),
})
export type CommonErrorResponse = z.infer<typeof COMMON_ERROR_RESPONSE_SCHEMA>