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

feat: Add Standard Schema validator to Qwik Router #7281

Draft
wants to merge 3 commits into
base: build/v2
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 2 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
6 changes: 4 additions & 2 deletions packages/qwik-router/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,17 @@
"bugs": "https://github.com/QwikDev/qwik/issues",
"dependencies": {
"@mdx-js/mdx": "^3",
"@standard-schema/spec": "^1.0.0-rc.0",
"@types/mdx": "^2",
"source-map": "^0.7.4",
"svgo": "^3.3",
"type-fest": "^4.33.0",
"undici": "*",
"valibot": ">=0.36.0 <2",
"valibot": "^1.0.0-beta.14",
"vfile": "6.0.2",
"vite": "^5",
"vite-imagetools": "^7",
"zod": "3.22.4"
"zod": "^3.24.1"
},
"devDependencies": {
"@azure/functions": "3.5.1",
Expand Down
3 changes: 0 additions & 3 deletions packages/qwik-router/src/runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ export type {
RouteNavigate,
StaticGenerate,
StaticGenerateHandler,
ValidatorErrorKeyDotNotation,
ValidatorErrorType,
ZodConstructor,
} from './types';
Expand Down Expand Up @@ -86,8 +85,6 @@ export {
usePreventNavigateQrl,
} from './use-functions';

export { z } from 'zod';

export { Form } from './form-component';
export type { FormProps } from './form-component';

Expand Down
117 changes: 64 additions & 53 deletions packages/qwik-router/src/runtime/src/server-functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ import type {
ServerConfig,
ServerFunction,
ServerQRL,
StandardSchemaConstructor,
StandardSchemaConstructorQRL,
StandardSchemaDataValidator,
ValibotConstructor,
ValibotConstructorQRL,
ValibotDataValidator,
Expand All @@ -56,6 +59,7 @@ import { isDev, isServer } from '@qwik.dev/core';

import type { FormSubmitCompletedDetail } from './form-component';
import { deepFreeze } from './utils';
import type { StandardSchemaV1 } from '@standard-schema/spec';

/** @internal */
export const routeActionQrl = ((
Expand Down Expand Up @@ -232,31 +236,60 @@ export const validatorQrl = ((
/** @public */
export const validator$: ValidatorConstructor = /*#__PURE__*/ implicit$FirstArg(validatorQrl);

const flattenValibotIssues = (issues: v.GenericIssue[]) => {
return issues.reduce<Record<string, string | string[]>>((acc, issue) => {
if (issue.path) {
const hasArrayType = issue.path.some((path) => path.type === 'array');
if (hasArrayType) {
const keySuffix = issue.expected === 'Array' ? '[]' : '';
const key =
issue.path
.map((item) => (item.type === 'array' ? '*' : item.key))
.join('.')
.replace(/\.\*/g, '[]') + keySuffix;
acc[key] = acc[key] || [];
if (Array.isArray(acc[key])) {
(acc[key] as string[]).push(issue.message);
/** @public */
export const schemaQrl: StandardSchemaConstructorQRL = (
qrl: QRL<StandardSchemaV1 | ((ev: RequestEvent) => StandardSchemaV1)>
): StandardSchemaDataValidator => {
if (isServer) {
return {
__brand: 'standard-schema',
async validate(ev, inputData) {
const schema: StandardSchemaV1 = await qrl
.resolve()
.then((obj) => (typeof obj === 'function' ? obj(ev) : obj));
const data = inputData ?? (await ev.parseBody());
const result = await schema['~standard'].validate(data);
if (!result.issues) {
return {
success: true,
data: result.value,
};
} else {
if (isDev) {
console.error('ERROR: Standard Schema validation failed', result.issues);
}
const formErrors: string[] = [];
const fieldErrors: Partial<Record<string, string[]>> = {};
for (const issue of result.issues) {
const dotPath = issue.path
?.map((item) => (typeof item === 'object' ? item.key : item))
.join('.');
if (dotPath) {
if (fieldErrors[dotPath]) {
fieldErrors[dotPath]!.push(issue.message);
} else {
fieldErrors[dotPath] = [issue.message];
}
} else {
formErrors.push(issue.message);
}
}
return {
success: false,
status: 400,
error: { formErrors, fieldErrors },
};
}
return acc;
} else {
acc[issue.path.map((item) => item.key).join('.')] = issue.message;
}
}
return acc;
}, {});
},
};
}
return undefined as never;
};

/** @internal */
/** @public */
export const schema$: StandardSchemaConstructor = /*#__PURE__*/ implicit$FirstArg(schemaQrl);

/** @deprecated */
export const valibotQrl: ValibotConstructorQRL = (
qrl: QRL<
| v.GenericSchema
Expand Down Expand Up @@ -287,12 +320,13 @@ export const valibotQrl: ValibotConstructorQRL = (
if (isDev) {
console.error('ERROR: Valibot validation failed', result.issues);
}
const flattErrors = v.flatten(result.issues);
return {
success: false,
status: 400,
error: {
formErrors: v.flatten(result.issues).root ?? [],
fieldErrors: flattenValibotIssues(result.issues),
formErrors: flattErrors.root ?? [],
fieldErrors: flattErrors.nested ?? {},
},
};
}
Expand All @@ -302,34 +336,10 @@ export const valibotQrl: ValibotConstructorQRL = (
return undefined as never;
};

/** @beta */
/** @deprecated */
export const valibot$: ValibotConstructor = /*#__PURE__*/ implicit$FirstArg(valibotQrl);

const flattenZodIssues = (issues: z.ZodIssue | z.ZodIssue[]) => {
issues = Array.isArray(issues) ? issues : [issues];
return issues.reduce<Record<string, string | string[]>>((acc, issue) => {
const isExpectingArray = 'expected' in issue && issue.expected === 'array';
const hasArrayType = issue.path.some((path) => typeof path === 'number') || isExpectingArray;
if (hasArrayType) {
const keySuffix = 'expected' in issue && issue.expected === 'array' ? '[]' : '';
const key =
issue.path
.map((path) => (typeof path === 'number' ? '*' : path))
.join('.')
.replace(/\.\*/g, '[]') + keySuffix;
acc[key] = acc[key] || [];
if (Array.isArray(acc[key])) {
(acc[key] as string[]).push(issue.message);
}
return acc;
} else {
acc[issue.path.join('.')] = issue.message;
}
return acc;
}, {});
};

/** @internal */
/** @deprecated */
export const zodQrl: ZodConstructorQRL = (
qrl: QRL<
z.ZodRawShape | z.Schema | ((z: typeof import('zod').z, ev: RequestEvent) => z.ZodRawShape)
Expand Down Expand Up @@ -357,12 +367,13 @@ export const zodQrl: ZodConstructorQRL = (
if (isDev) {
console.error('ERROR: Zod validation failed', result.error.issues);
}
const flattErrors = result.error.flatten();
return {
success: false,
status: 400,
error: {
formErrors: result.error.flatten().formErrors,
fieldErrors: flattenZodIssues(result.error.issues),
formErrors: flattErrors.formErrors,
fieldErrors: flattErrors.fieldErrors,
},
};
}
Expand All @@ -372,7 +383,7 @@ export const zodQrl: ZodConstructorQRL = (
return undefined as never;
};

/** @public */
/** @deprecated */
export const zod$: ZodConstructor = /*#__PURE__*/ implicit$FirstArg(zodQrl);

/** @internal */
Expand Down
Loading
Loading