typescriptadvanced

OpenAPI Request Validator

Validates incoming request body against a JSON schema derived from an OpenAPI spec.

typescript
import { Request, Response, NextFunction } from 'express';

interface SchemaProperty {
  type: string;
  required?: boolean;
  minLength?: number;
  pattern?: string;
}

interface Schema {
  [key: string]: SchemaProperty;
}

function validate(data: Record<string, unknown>, schema: Schema): string[] {
  const errors: string[] = [];
  for (const [field, rules] of Object.entries(schema)) {
    const value = data[field];
    if (rules.required && (value === undefined || value === null)) {
      errors.push(`${field} is required`);
      continue;
    }
    if (value !== undefined && typeof value !== rules.type) {
      errors.push(`${field} must be of type ${rules.type}`);
    }
    if (rules.minLength && typeof value === 'string' && value.length < rules.minLength) {
      errors.push(`${field} must be at least ${rules.minLength} characters`);
    }
  }
  return errors;
}

export function validateBody(schema: Schema) {
  return (req: Request, res: Response, next: NextFunction) => {
    const errors = validate(req.body, schema);
    if (errors.length > 0) {
      return res.status(422).json({ errors });
    }
    next();
  };
}

Use Cases

  • API input validation
  • Contract-first development

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.