sailfork / t3code-github / .repos/ alchemy-effect/ packages/ integration-tests/ test/ Git/ fixtures/ http.ts

/** Standard Effect HTTP group registration with an application user handler. */
import { GitApi, GroupsLive, InternalApiLive, Handlers } from "@alchemy.run/git";
import * as Http from "alchemy/Http";
import * as Effect from "effect/Effect";
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { TestCaller, TestAuthLive } from "./test-auth.ts";

export const GitHubLive = HttpApiBuilder.group(GitApi, "github", (h) =>
  Effect.map(Handlers, (git) =>
    h.handleAll({
      ...git.github,
      user: () =>
        Effect.gen(function* () {
          const caller = yield* Effect.serviceOption(TestCaller);
          const user = Option.isSome(caller) ? caller.value.user : null;
          return user === null
            ? HttpServerResponse.jsonUnsafe({ message: "Requires authentication" }, { status: 401 })
            : HttpServerResponse.jsonUnsafe({
                login: user.name,
                id: 1,
                type: "User",
              });
        }),
    }),
  ),
);

/** The test application's router: public Git routes plus the internal hash route. */
export const TestRoutes = Layer.mergeAll(
  HttpApiBuilder.layer(GitApi).pipe(
    Layer.provide(Layer.mergeAll(GroupsLive, GitHubLive)),
    Layer.provide(TestAuthLive),
  ),
  InternalApiLive,
).pipe(Layer.provide(Http.Platform));