0.1.0Updated 7 months ago
import { Context, Router, RouterContext } from "jsr:@oak/oak@^17.1.4";
import Host from "./modules/host/host.ts";
import { ContextState } from "./modules/host/context_state.ts";
import { InfinityRequest } from "./modules/networking/infinity_request.ts";
import { InfinityRequestHandler } from "./types/networking.d.ts";

import { Sluggify } from "./utils/slug.ts";

interface I_Infinity {
  /** The name of this Infinity application */
  name: string
  /** The port the Host should use to listen for API and Worker events
   * 
   * Default: 9090
   * Also tries to read from `PORT` value in the environment
   */
  port?: number
}

export default interface Infinity extends I_Infinity {}
export default class Infinity {
  protected host: Host
  readonly name: string

  constructor({ name, port }: I_Infinity) {
    this.name = name;
    this.host = new Host({ port });
  }

  get slug() {
    return Sluggify(this.name);
  }

  get port() {
    return this.host.port;
  }

  listen(callback?: (port: number) => void) {
    this.host.listen(callback);
  }

  get(path: string, handler: InfinityRequestHandler) {
    // deno-lint-ignore ban-types
    this.host.router.get(path, async (ctx: RouterContext<string, {}, Context<ContextState>>, next) => {
      const request = new InfinityRequest(ctx);
      await request.init();

      await handler(request, request.res, next);
    })
  }

  post(path: string, handler: InfinityRequestHandler) {
    // deno-lint-ignore ban-types
    this.host.router.post(path, async (ctx: RouterContext<string, {}, Context<ContextState>>, next) => {
      const request = new InfinityRequest(ctx);
      await request.init();

      await handler(request, request.res, next);
    })
  }

  static get Router(): typeof Router {
    return Router;
  }
}