WayrApp Backend & Ecosystem Documentation - v1.0.0
    Preparing search index...

    Function validateBody

    • Convenience middleware factory for request body validation only

      Creates Express middleware that validates only the request body against a Zod schema, ignoring URL parameters and query strings. This function provides a streamlined API for the common use case of validating POST, PUT, and PATCH request bodies without the need to specify the full schema object structure.

      This middleware is particularly useful for API endpoints that accept JSON payloads for creating or updating resources, where URL parameters and query strings are either not used or validated separately. It maintains the same validation behavior and error handling as the main validate function while providing a more concise syntax.

      The function internally delegates to the main validate function, ensuring consistent behavior and error handling across all validation middleware. This approach maintains code reusability while providing developer-friendly convenience functions.

      Parameters

      • schema: ZodType

        Zod schema for validating the request body

      Returns (req: Request, _res: Response, next: NextFunction) => void

      Express middleware function that validates request body

      When body validation fails, forwards error to global error handler

      When non-Zod errors occur during validation

      // User registration endpoint
      const registerSchema = z.object({
      email: z.string().email('Invalid email format'),
      password: z.string().min(8, 'Password must be at least 8 characters'),
      firstName: z.string().min(1, 'First name is required'),
      lastName: z.string().min(1, 'Last name is required'),
      acceptTerms: z.boolean().refine(val => val === true, 'Must accept terms')
      });

      router.post('/auth/register', validateBody(registerSchema), authController.register);
      // Course creation with nested validation
      const courseSchema = z.object({
      title: z.string().min(1, 'Title is required').max(200),
      description: z.string().max(1000).optional(),
      difficulty: z.enum(['beginner', 'intermediate', 'advanced']),
      modules: z.array(z.object({
      title: z.string().min(1),
      order: z.number().int().min(0)
      })).min(1, 'At least one module is required')
      });

      router.post('/courses', validateBody(courseSchema), courseController.create);
      // Update user profile
      const updateProfileSchema = z.object({
      firstName: z.string().min(1).optional(),
      lastName: z.string().min(1).optional(),
      bio: z.string().max(500).optional(),
      preferences: z.object({
      language: z.string().optional(),
      notifications: z.boolean().optional()
      }).optional()
      });

      router.put('/profile', validateBody(updateProfileSchema), userController.updateProfile);