.ts
TypeScript
(application/typescript)
// 1st-party
import { ReqHandler } from "@ethicdevs/react-monolith";
// app
import { AppRoute, AppRoutesParams } from "../../routes";
// app islands
import {
  PullRequestFormState,
  RepositoryPullRequestCreateFormVariant,
} from "../../islands/RepositoryPullRequestCreateForm";
// app services
import { makeOrganizationService } from "../../services/organization";
import { makeRepositoryService } from "../../services/repository";
// app views
import RepositoryPullRequestCreateView, {
  RepositoryPullRequestCreateViewProps,
} from "../../views/repository/RepositoryPullRequestCreateView";

const postRepositoryPullRequestCreateAction: ReqHandler = async (
  request,
  reply
) => {
  const { orgSlug, repoSlug } =
    request.params as AppRoutesParams[AppRoute.REPOSITORY_PULL_REQUEST_CREATE_ACTION]["params"];
  const { state_from: fromState, state_dest: desiredState } =
    request.body as AppRoutesParams[AppRoute.REPOSITORY_PULL_REQUEST_CREATE_ACTION]["body"];

  const orgService = makeOrganizationService({ request });
  const repoService = makeRepositoryService({ request });

  const parentOrg = await orgService.getOrganizationBySlug(orgSlug);
  const repo = await repoService.getRepository(orgSlug, repoSlug);

  if (parentOrg == null || repo == null) {
    return reply.status(404).callNotFound();
  }

  if (
    fromState === PullRequestFormState.ERROR ||
    desiredState === PullRequestFormState.CONFIGURE
  ) {
    let redirectUri =
      request.namedViewsPathMap[AppRoute.REPOSITORY_PULL_REQUEST_CREATE];
    redirectUri = redirectUri
      .replace(/:orgSlug/g, parentOrg.slug)
      .replace(/:repoSlug/g, repo.slug);
    reply.redirect(302, redirectUri);
    return reply;
  }

  let variant: RepositoryPullRequestCreateFormVariant | null = null;

  if (desiredState === PullRequestFormState.COMPARE) {
    variant = {
      state: desiredState,
      data: {
        source: {
          parentOrg,
          repo,
          branch: "",
        },
        target: {
          parentOrg,
          repo,
          branch: "",
        },
      },
    };
  } else if (desiredState === PullRequestFormState.DETAILS) {
    variant = {
      state: desiredState,
      data: {
        canCurrentUserSubmitPullRequest: false,
      },
    };
  }

  if (variant == null) {
    variant = {
      state: PullRequestFormState.ERROR,
      data: {
        errorMessage: "Something went wrong",
      },
    };
  }

  const reqHandler = reply.makeRequestHandler(request, reply);
  return reqHandler<RepositoryPullRequestCreateViewProps>(
    RepositoryPullRequestCreateView.name,
    {
      errorMessage: null,
      initialValues: {},
      parentOrg,
      repo,
      variant,
    }
  );
};

export default postRepositoryPullRequestCreateAction;