@energica-city/shared-amplify-utils
Version:
Shared utilities for AWS Amplify projects
90 lines • 3.51 kB
TypeScript
import type { Middleware } from '../middlewareChain';
import type { WebSocketEvent, WebSocketInputWithModels, WebSocketResponse, WebSocketRequestValidationConfig } from './types';
import type { AmplifyModelType } from '../../queries/types';
/**
* Retrieve validated message data from a WebSocket event
*
* This function extracts the validated message data that was stored by the
* WebSocket request validator middleware. Returns undefined if no validation
* was performed or if validation failed.
*
* @template T - Type of the validated message data
* @param event - The WebSocket event that may contain validated data
* @returns The validated message data, or undefined if not available
*
* @example
* ```typescript
* interface MessageData {
* action: string;
* payload: Record<string, unknown>;
* }
*
* const validatedMessage = getValidatedMessage<MessageData>(event);
* if (validatedMessage) {
* console.log('Action:', validatedMessage.action);
* }
* ```
*/
export declare function getValidatedMessage<T = unknown>(event: WebSocketEvent): T | undefined;
/**
* Create a WebSocket request validation middleware
*
* This middleware validates incoming WebSocket message bodies against a Yup schema.
* It only validates MESSAGE events (not CONNECT/DISCONNECT) and can be configured
* to validate only specific routes.
*
* **Validation Process:**
* 1. Checks if validation should be performed (MESSAGE event, has schema, etc.)
* 2. Parses the JSON message body
* 3. Validates against the provided Yup schema
* 4. Stores validated data on the event for later retrieval
* 5. Continues to next middleware with original input
*
* **Error Handling:**
* - JSON parsing errors: Returns BAD_REQUEST with context
* - Validation errors: Returns BAD_REQUEST with validation details
* - Other errors: Returns INTERNAL_SERVER_ERROR
*
* **Validated Data Access:**
* Use `getValidatedMessage<T>(event)` to retrieve validated data in subsequent middleware.
*
* @template TTypes - Record of available Amplify model types
* @template TSelected - Selected model types for this middleware chain
* @template TOutput - Expected output type of the middleware chain
* @param config - Configuration options for validation behavior
* @returns Middleware function for WebSocket request validation
*
* @example
* ```typescript
* import * as yup from 'yup';
*
* const messageSchema = yup.object({
* action: yup.string().required(),
* payload: yup.object().required(),
* timestamp: yup.number().optional(),
* });
*
* const validator = createWebSocketRequestValidator({
* bodySchema: messageSchema,
* validateOnlyOnRoutes: ['sendMessage', 'updateStatus'],
* stripUnknown: true,
* errorMessage: 'Invalid message format',
* });
*
* chain.use('validation', validator);
* ```
*
* @example
* ```typescript
* // In your handler, retrieve validated data:
* const handler = async (input) => {
* const validatedMessage = getValidatedMessage<MessageData>(input.event);
* if (validatedMessage) {
* // Process validated message
* return { statusCode: 200 };
* }
* };
* ```
*/
export declare function createWebSocketRequestValidator<TTypes extends Record<string, AmplifyModelType>, TSelected extends keyof TTypes & string = keyof TTypes & string, TOutput = WebSocketResponse>(config: WebSocketRequestValidationConfig): Middleware<WebSocketInputWithModels<TTypes, TSelected>, TOutput>;
//# sourceMappingURL=WebSocketRequestValidator.d.ts.map