Function getBody

Extracts the body from the request and validates it against the route's body schema

  • Type Parameters

    • S extends ZodType<any, ZodTypeDef, any> = ZodType<any, ZodTypeDef, any>

    Parameters

    • request: Request

      The incoming HTTP request

    • route: Route<S>

      The route that contains the body schema.

    Returns Promise<any>

    The body of the request, or null if the route does not have a body schema.

    Example usage:

    import { router, text, getBody } from "@pulsar-http/core";
    import z from 'zod';

    const userSchema = z.object({
    name: z.string(),
    email: z.string().email(),
    });

    // Schema must be passed to the route if you want to use `body` in the handler or `getBody` function.
    // If not passed, you can retrieve the body from the request object as usual.
    const myRoute = router.post('/api/users', async () => text('User Created'), {
    bodySchema: userSchema,
    });

    // Fake the request for the example
    const request = new Request('http://localhost:3000/api/users', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    },
    body: JSON.stringify({ name: 'John Doe', email: 'john@example.com' }),
    });

    const body = await getBody(request, myRoute);

    console.log(body); // Output: { name: 'John Doe', email: 'john@example.com' }