Skip to content

HTTP Helper Utilities

This file provides utility functions for the @sodacore/core HTTP module. These helpers assist with route matching, parameter extraction, cookie parsing, and converting various values to standardized HTTP Response objects.


Features

  • Route Matching: Functions to check if a URL path matches a route pattern.
  • Parameter Extraction: Extracts route parameters from URL paths based on route definitions.
  • Cookie Parsing: Parses cookie strings into a convenient Map for easy access.
  • Response Conversion: Converts various types of values (errors, objects, strings, booleans, etc.) into HTTP Response objects with appropriate status codes and headers.

Usage

Import and use these helpers in your HTTP controllers, middleware, or services:

typescript
import { doesRouteMatch, getRouteParams, parseCookies, toResponse } from './helper/utils';

const match = doesRouteMatch('/users/:id', '/users/123'); // true
const params = getRouteParams('/users/:id', '/users/123'); // { id: '123' }
const cookies = parseCookies('foo=bar; session=abc'); // Map { 'foo' => 'bar', 'session' => 'abc' }
const response = toResponse({ message: 'ok' }); // Response object with JSON body

API

doesRouteMatch(path: string, value: string): boolean

Checks if a given URL path matches a route pattern (supports parameters like :id).

getRouteParams(route: string, path: string): Record<string, string>

Extracts named parameters from a URL path based on the route definition.

parseCookies(cookies: string): Map<string, string>

Parses a cookie string into a Map of key-value pairs.

toResponse(value: any): Response

Converts a value to a standardized HTTP Response object:

  • If Response, returns as-is.
  • If Error, returns a 500 response with the error message.
  • If null, returns a 404 response.
  • If string or number, returns a 200 response with the value as the body.
  • If object, returns a 200 response with a JSON body.
  • If true, returns a 201 response.
  • If false, returns a 400 response.
  • If undefined, returns a 204 response.

Notes

  • These helpers are designed for internal use by the Sodacore HTTP framework but can be used in custom modules as well.
  • The toResponse function ensures consistent HTTP responses from controller methods, regardless of the return type.

Released under the Apache-2.0 License.