Home Reference Source

terrier-repo/bodyparser/mod.ts

import { splitQueryString } from "./splitQueryString.ts";
import { getQueryString } from "./getQueryString.ts";
import { seperateQueries } from "./seperateQueries.ts";

/**
 * URL metadata
 * @interface
 */
interface ParserURL {
  PathWithoutQueryString: string;
  QueryString: string;
  SeperatedQueries: string[];
}

/**
 * Body parser for Terrier
 * @example
 * const parser = new Parser(req.url);
 */
export class Parser {
  /**
   * URL metadata
   * @protected
   */
  protected url: ParserURL;

  /**
   * Initiate the body parser with the request URL
   * @param url The request URL
   */
  constructor(url) {
    const PathWithoutQueryString = splitQueryString(url);
    const QueryString = getQueryString(url);
    const SeperatedQueries = seperateQueries(QueryString);
    this.url = {
      PathWithoutQueryString,
      QueryString,
      SeperatedQueries
    };
  }

  /**
   * Get the query string from URL
   * @return {string} URL query string
   */
  public getQueryString = () => {
    return this.url.QueryString;
  };

  /**
   * Get the request URL without query string
   * @return {string} request URL without query string
   */
  public getPathWithoutQuery = () => {
    return this.url.PathWithoutQueryString;
  };

  /**
   * Get seperated raw queries
   * @return {array} Raw queries as array
   */
  public getSeperatedQueries = () => {
    return this.url.SeperatedQueries;
  };

  /**
   * Get the value of a query
   * @param query The query name you are looking for
   * @return {string} The value of query
   */
  public getValue = (query: string) => {
    const vars = this.url.SeperatedQueries;
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split("=");
      if (decodeURIComponent(pair[0]) == query) {
        return decodeURIComponent(pair[1]);
      }
    }
    return new Error(`Query ${query} not found`);
  };
}