Typed Query String Parser

Parse URL query strings into typed values with reusable string, integer, boolean, list, and enum decoders plus aggregated errors.

TypescriptData Fetching

Code

typescriptsnippet
225 lines
export class QueryParseError extends Error {
  public readonly issues: string[];

  public constructor(issues: readonly string[]) {
    super(issues.join("; "));
    this.name = "QueryParseError";
    this.issues = [...issues];
  }
}

export type QueryDecoder<T> = (
  values: readonly string[],
  key: string,
) => T;

function single(values: readonly string[], key: string): string | undefined {
  if (values.length > 1) {
    throw new QueryParseError([`${key} must be provided at most once`]);
  }
  return values[0];
}

export interface StringOptions {
  default?: string;
  minLength?: number;
}

export function stringParam(options: StringOptions = {}): QueryDecoder<string> {
  const { default: defaultValue, minLength } = options;
  if (minLength !== undefined && (!Number.isInteger(minLength) || minLength < 0)) {
    throw new RangeError("minLength must be a non-negative integer");
  }
  if (defaultValue !== undefined && typeof defaultValue !== "string") {
    throw new TypeError("default must be a string");
  }
  if (
    defaultValue !== undefined &&
    minLength !== undefined &&
    defaultValue.length < minLength
  ) {
    throw new RangeError("default must satisfy minLength");
  }
  return (values, key) => {
    const raw = single(values, key);
    if (raw === undefined) {
      if (defaultValue !== undefined) return defaultValue;
      throw new QueryParseError([`${key} is required`]);
    }
    if (minLength !== undefined && raw.length < minLength) {
      throw new QueryParseError([
        `${key} must be at least ${minLength} characters`,
      ]);
    }
    return raw;
  };
}

export interface IntegerOptions {
  default?: number;
  min?: number;
  max?: number;
}

export function integerParam(options: IntegerOptions = {}): QueryDecoder<number> {
  const { default: defaultValue, min, max } = options;
  if (
    defaultValue !== undefined &&
    (!Number.isSafeInteger(defaultValue) ||
      (min !== undefined && defaultValue < min) ||
      (max !== undefined && defaultValue > max))
  ) {
    throw new RangeError("default must satisfy the integer bounds");
  }
  return (values, key) => {
    const raw = single(values, key);
    if (raw === undefined) {
      if (defaultValue !== undefined) return defaultValue;
      throw new QueryParseError([`${key} is required`]);
    }
    if (!/^-?\d+$/.test(raw)) {
      throw new QueryParseError([`${key} must be an integer`]);
    }
    const value = Number(raw);
    if (!Number.isSafeInteger(value)) {
      throw new QueryParseError([`${key} is outside the safe integer range`]);
    }
    if ((min !== undefined && value < min) || (max !== undefined && value > max)) {
      throw new QueryParseError([
        `${key} must be between ${min ?? "-Infinity"} and ${max ?? "Infinity"}`,
      ]);
    }
    return value;
  };
}

export interface BooleanOptions {
  default?: boolean;
}

export function booleanParam(options: BooleanOptions = {}): QueryDecoder<boolean> {
  const { default: defaultValue } = options;
  return (values, key) => {
    const raw = single(values, key);
    if (raw === undefined) {
      if (defaultValue !== undefined) return defaultValue;
      throw new QueryParseError([`${key} is required`]);
    }
    const normalized = raw.toLowerCase();
    if (["1", "true", "yes", "on"].includes(normalized)) return true;
    if (["0", "false", "no", "off"].includes(normalized)) return false;
    throw new QueryParseError([`${key} must be a boolean`]);
  };
}

export interface ListOptions {
  default?: readonly string[];
  minItems?: number;
}

export function listParam(options: ListOptions = {}): QueryDecoder<string[]> {
  const { default: defaultValue = [], minItems } = options;
  return (values, key) => {
    const items = values.length > 0 ? [...values] : [...defaultValue];
    if (minItems !== undefined && items.length < minItems) {
      throw new QueryParseError([
        `${key} must contain at least ${minItems} values`,
      ]);
    }
    return items;
  };
}

export function enumParam<const T extends readonly string[]>(
  allowed: T,
  options: { default?: T[number] } = {},
): QueryDecoder<T[number]> {
  if (!Array.isArray(allowed) || allowed.length === 0) {
    throw new RangeError("allowed values must not be empty");
  }
  const allowedSet = new Set<string>(allowed);
  const { default: defaultValue } = options;
  if (defaultValue !== undefined && !allowedSet.has(defaultValue)) {
    throw new RangeError("default must be one of the allowed values");
  }
  return (values, key) => {
    const raw = single(values, key);
    if (raw === undefined) {
      if (defaultValue !== undefined) return defaultValue;
      throw new QueryParseError([`${key} is required`]);
    }
    if (!allowedSet.has(raw)) {
      throw new QueryParseError([
        `${key} must be one of: ${allowed.join(", ")}`,
      ]);
    }
    return raw as T[number];
  };
}

export function parseQuery<
  T extends Record<string, QueryDecoder<unknown>>,
>(
  input: string | URLSearchParams,
  schema: T,
  options: { strict?: boolean } = {},
): { [K in keyof T]: T[K] extends QueryDecoder<infer V> ? V : never } {
  const { strict = true } = options;
  const params =
    typeof input === "string"
      ? new URLSearchParams(input.startsWith("?") ? input.slice(1) : input)
      : input;

  if (strict) {
    for (const key of params.keys()) {
      if (!Object.prototype.hasOwnProperty.call(schema, key)) {
        throw new QueryParseError([`unknown parameter "${key}"`]);
      }
    }
  }

  const result = {} as {
    [K in keyof T]: T[K] extends QueryDecoder<infer V> ? V : never;
  };
  const issues: string[] = [];
  for (const key of Object.keys(schema) as Array<keyof T>) {
    const decoder = schema[key];
    try {
      const value = decoder(params.getAll(String(key)), String(key));
      (result as unknown as Record<string, unknown>)[String(key)] = value;
    } catch (error) {
      if (error instanceof QueryParseError) issues.push(...error.issues);
      else throw error;
    }
  }
  if (issues.length > 0) throw new QueryParseError(issues);
  return result;
}

const schema = {
  q: stringParam({ default: "all", minLength: 2 }),
  page: integerParam({ default: 1, min: 1 }),
  active: booleanParam({ default: false }),
  tags: listParam({ default: [] }),
  sort: enumParam(["newest", "oldest"], { default: "newest" }),
};

const parsed = parseQuery(
  "?q=router&page=2&active=true&tags=api&tags=node",
  schema,
);
console.log(parsed);
const page: number = parsed.page;
console.log(page + 1);

try {
  parseQuery("?page=0&active=maybe", schema, { strict: false });
} catch (error) {
  if (error instanceof QueryParseError) console.log(error.issues);
}

try {
  parseQuery("?page=1&extra=1", schema);
} catch (error) {
  if (error instanceof QueryParseError) console.log(error.issues);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

{
  q: 'router',
  page: 2,
  active: true,
  tags: [ 'api', 'node' ],
  sort: 'newest'
}
3
[ 'page must be between 1 and Infinity', 'active must be a boolean' ]
[ 'unknown parameter "extra"' ]

How it works

The snippet is organized around the class QueryParseError and the functions single, stringParam, integerParam and booleanParam.

Iteration is nested: for (const key of params.keys()) frames the pass, for (const key of Object.keys(schema) as Array<keyof T>) does the per-item step. When the guard condition holds, QueryParseError, RangeError and TypeError is thrown rather than a bogus value returned.

What to watch for

  • The guard values.length > 1 short-circuits the flow with an early throw when its condition holds.

Applying it

Import QueryParseError from the file and call it — the rest of the code is implementation detail.

Statements that matter

[K in keyof T]: T[K] extends QueryDecoder<infer V> ? V : never;
return (values, key) => {
  const items = values.length > 0 ? [...values] : [...defaultValue];
  if (minItems !== undefined && items.length < minItems) {
    throw new QueryParseError([
      `${key} must contain at least ${minItems} values`,
    ]);
  }
  return items;
};
throw new QueryParseError([`${key} is outside the safe integer range`]);

Interactive Tools for This Topic

FAQ

How does the snippet fail?
The code refuses to continue: `QueryParseError`, `RangeError` and `TypeError` is thrown while the state is still recoverable.
Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `single`, `stringParam`, `integerParam` at load time.