parent
e8281ebf83
commit
4fa2e7e600
@ -0,0 +1,40 @@
|
||||
import type { StandardSchemaV1 } from '$libs/standard-schema';
|
||||
import {
|
||||
HTTP_DIAGNOSTIC_EVENTS,
|
||||
requestBodyValidationErrorMessage
|
||||
} from './consts.ts';
|
||||
import { emitHttpDiagnostic, type HttpDiagnostics } from './diagnostics.ts';
|
||||
import { HttpBodyValidationError } from './errors.ts';
|
||||
import { runStandardValidate } from './results.ts';
|
||||
import type { HttpMethod } from './types.ts';
|
||||
|
||||
interface ValidateHttpRequestBodyInput {
|
||||
readonly diagnostics: HttpDiagnostics;
|
||||
readonly method: HttpMethod;
|
||||
readonly url: string;
|
||||
readonly body: unknown;
|
||||
readonly schema: StandardSchemaV1 | undefined;
|
||||
}
|
||||
|
||||
export async function validateHttpRequestBody(
|
||||
input: ValidateHttpRequestBodyInput
|
||||
): Promise<void> {
|
||||
if (input.body === undefined || input.schema === undefined) return;
|
||||
|
||||
const validated = await runStandardValidate(input.schema, input.body);
|
||||
if (validated.issues === undefined) return;
|
||||
|
||||
const error = new HttpBodyValidationError(
|
||||
requestBodyValidationErrorMessage(input.method, input.url),
|
||||
validated.issues
|
||||
);
|
||||
// Programmer error: log it before throwing so the failure is visible in
|
||||
// the logger pipeline even when the caller's catch swallows the throw.
|
||||
emitHttpDiagnostic(input.diagnostics, HTTP_DIAGNOSTIC_EVENTS.BODY_SCHEMA_REJECTED, {
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
issueCount: validated.issues.length,
|
||||
error
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
Loading…
Reference in new issue