.ts
TypeScript
(application/typescript)
// 3rd-party
import type {
  ContextConfigDefault,
  FastifyContextConfig,
  preHandlerHookHandler,
} from "fastify";
// app
import type { RepositoryCountersDTO } from "../../types";
import { makeRepositoryService } from "../../services/repository";

declare module "fastify" {
  export interface FastifyContext<ContextConfig = ContextConfigDefault> {
    config: FastifyContextConfig & ContextConfig;
    layoutCounters: RepositoryCountersDTO;
  }
}

export const loadRepositoryCounters: preHandlerHookHandler = async (
  request,
  reply,
  done,
) => {
  const { orgSlug, repoSlug, username } = request.params as any;
  if (orgSlug == null || repoSlug == null) {
    reply.context.layoutCounters = {
      files: 0,
      forks: 0,
      branches: 0,
      tags: 0,
      commits: 0,
      pulls: 0,
      tests: 0,
      builds: 0,
      issues: 0,
      apiRefSymbols: 0,
      helpCenterNotifs: 0,
      sshKeys: 0,
    };
    done();
    return;
  }
  const repoService = makeRepositoryService({ request });
  const counters = await repoService.getRepositoryCounters(
    orgSlug,
    repoSlug,
    username,
  );
  reply.context.layoutCounters = counters;
  done();
};