import { InMemoryCacheAdapter } from "@ethicdevs/fastify-stream-react-views";
import type { ServiceMethodFactory } from "@ethicdevs/react-monolith";
import { RepositoryCountersDTO } from "../../types";
import type { RepositoryServiceDeps } from "./types";
const CACHE = new InMemoryCacheAdapter();
const CACHE_TTL = 30 * 1000;
const makeGetRepositoryCounters: ServiceMethodFactory<
RepositoryServiceDeps,
[string, string, string | null],
Promise<RepositoryCountersDTO | null>
> = ({ request }) => {
return async (orgSlug, repoSlug, username) => {
const cacheKey = `${orgSlug}/${repoSlug}/counters`;
const lastRefresh = await CACHE.get(
`${orgSlug}/${repoSlug}/counters/lastRefresh`,
);
let isFreshCache = (request.params as any)["refetch"] != null || false;
if (
lastRefresh != null &&
new Date(lastRefresh).getTime() > Date.now() - CACHE_TTL
) {
isFreshCache = true;
}
if (isFreshCache === false && (await CACHE.has(cacheKey))) {
const value = await CACHE.get(cacheKey);
if (value) return JSON.parse(value);
return DEFAULT_COUNTERS;
}
const openPulls =
orgSlug != null && repoSlug != null
? await request.prisma.pullRequest.count({
where: {
targetRepository: {
organization: { slug: orgSlug },
slug: repoSlug,
},
state: "OPEN",
closedAt: null,
},
})
: 0;
const sshKeys =
username != null
? await request.prisma.userSSHKey.count({
where: {
user: {
username: username!,
},
revoked: false,
},
})
: 0;
const counters: RepositoryCountersDTO = {
files: 0,
forks: 0,
branches: 0,
tags: 0,
commits: 0,
pulls: openPulls,
tests: 0,
builds: 0,
issues: 0,
apiRefSymbols: 0,
helpCenterNotifs: 0,
sshKeys: sshKeys,
};
console.log("COUNTERS=", counters);
await CACHE.set(cacheKey, JSON.stringify(counters));
return counters;
};
};
const DEFAULT_COUNTERS: RepositoryCountersDTO = {
files: 0,
forks: 0,
branches: 0,
tags: 0,
commits: 0,
pulls: 0,
tests: 0,
builds: 0,
issues: 0,
apiRefSymbols: 0,
helpCenterNotifs: 0,
sshKeys: 0,
};
export default makeGetRepositoryCounters;