master
Raw Download raw file
 1// From https://github.com/gajus/slonik?tab=readme-ov-file#result-parser-interceptor
 2import { type Interceptor, type QueryResultRow, SchemaValidationError } from "slonik";
 3
 4export const createResultParserInterceptor = (): Interceptor => {
 5	return {
 6		// If you are not going to transform results using Zod, then you should use `afterQueryExecution` instead.
 7		// Future versions of Zod will provide a more efficient parser when parsing without transformations.
 8		// You can even combine the two – use `afterQueryExecution` to validate results, and (conditionally)
 9		// transform results as needed in `transformRow`.
10		transformRow: async (executionContext, actualQuery, row) => {
11			const { log, resultParser } = executionContext;
12
13			if (!resultParser) {
14				return row;
15			}
16
17			// It is recommended (but not required) to parse async to avoid blocking the event loop during validation
18			const validationResult = await resultParser.safeParseAsync(row);
19
20			if (!validationResult.success) {
21				throw new SchemaValidationError(actualQuery, row, validationResult.error.issues);
22			}
23
24			return validationResult.data as QueryResultRow;
25		},
26	};
27};