Function isValidHttpMethod

  • Validates whether a value is a supported HTTP method.

    This function performs strict validation to ensure the input is exactly one of the supported HTTP methods. It's case-sensitive and requires exact string matches.

    Validation Rules:

    • Input must be a string
    • Input must exactly match one of the supported methods
    • Case-sensitive comparison (GET is valid, get is not)
    • No whitespace or special characters allowed

    Type Guard: This function acts as a TypeScript type guard, narrowing the type from unknown to HttpMethod when it returns true.

    Parameters

    • method: unknown

      The value to validate

    Returns method is HttpMethod

    true if the method is valid, false otherwise

    // Valid methods
    isValidHttpMethod('GET'); // true
    isValidHttpMethod('POST'); // true
    isValidHttpMethod('PUT'); // true
    isValidHttpMethod('DELETE'); // true
    isValidHttpMethod('PATCH'); // true
    isValidHttpMethod('HEAD'); // true
    isValidHttpMethod('OPTIONS'); // true

    // Invalid methods
    isValidHttpMethod('get'); // false (case sensitive)
    isValidHttpMethod('GETS'); // false (typo)
    isValidHttpMethod(''); // false (empty string)
    isValidHttpMethod(null); // false (not a string)
    isValidHttpMethod(123); // false (not a string)
    isValidHttpMethod('TRACE'); // false (not supported)

    // Usage in validation
    function handleRequest(method) {
    if (!isValidHttpMethod(method)) {
    throw new Error(`Invalid HTTP method: ${method}`);
    }
    // method is now typed as HttpMethod
    console.log(`Processing ${method} request`);
    }

    // Type guard usage
    function processMethod(input) {
    if (isValidHttpMethod(input)) {
    // input is now typed as HttpMethod
    return `Valid method: ${input}`;
    } else {
    // input is still unknown
    return `Invalid method: ${input}`;
    }
    }