Skip to content

Commit

Permalink
feat: request azure
Browse files Browse the repository at this point in the history
  • Loading branch information
alexcastrodev committed Sep 30, 2023
1 parent d203af7 commit f3363f1
Show file tree
Hide file tree
Showing 6 changed files with 162 additions and 10 deletions.
6 changes: 1 addition & 5 deletions api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,9 @@ import { COLORS, Theme } from "../src/theme.ts";
import { Error400 } from "../src/error_page.ts";
import "https://deno.land/x/[email protected]/load.ts";
import { staticRenderRegeneration } from "../src/StaticRenderRegeneration/index.ts";
import { GithubRepositoryService } from "../src/Repository/GithubRepository.ts";
import { GithubApiService } from "../src/Services/GithubApiService.ts";
import { ServiceError } from "../src/Types/index.ts";
import { ErrorPage } from "../src/pages/Error.ts";

const serviceProvider = new GithubApiService();
const client = new GithubRepositoryService(serviceProvider).repository;
import { client } from "../src/Services/index.ts";

const defaultHeaders = new Headers(
{
Expand Down
9 changes: 7 additions & 2 deletions deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@ import {
spy,
} from "https://deno.land/[email protected]/testing/mock.ts";

import { CONSTANTS } from "./src/utils.ts";
const api = new Map([
["github", Deno.env.get("GITHUB_API")],
["azure", Deno.env.get("AZURE_API_URL")],
]);

const baseURL = Deno.env.get("GITHUB_API") || CONSTANTS.DEFAULT_GITHUB_API;
const DEFAULT_PROVIDER = Deno.env.get("provider") ?? "github";

const baseURL = api.get(DEFAULT_PROVIDER);

const soxa = new ServiceProvider({
...defaults,
Expand Down
128 changes: 128 additions & 0 deletions src/Services/GithubAzureService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { GithubRepository } from "../Repository/GithubRepository.ts";
import {
GitHubUserActivity,
GitHubUserIssue,
GitHubUserPullRequest,
GitHubUserRepository,
UserInfo,
} from "../user_info.ts";
import {
queryUserActivity,
queryUserIssue,
queryUserPullRequest,
queryUserRepository,
} from "../Schemas/index.ts";
import { soxa } from "../../deps.ts";
import { Retry } from "../Helpers/Retry.ts";
import {
EServiceKindError,
QueryDefaultResponse,
ServiceError,
} from "../Types/index.ts";
import { CONSTANTS } from "../utils.ts";

const authentication = Deno.env.get("X_API_KEY");

export const TOKENS = [
Deno.env.get("GITHUB_TOKEN1"),
Deno.env.get("GITHUB_TOKEN2"),
];

export class GithubAzureService extends GithubRepository {
async requestUserRepository(
username: string,
): Promise<GitHubUserRepository | ServiceError> {
return await this.executeQuery<GitHubUserRepository>(queryUserRepository, {
username,
}, "userRepository");
}
async requestUserActivity(
username: string,
): Promise<GitHubUserActivity | ServiceError> {
return await this.executeQuery<GitHubUserActivity>(queryUserActivity, {
username,
}, "userActivity");
}
async requestUserIssue(
username: string,
): Promise<GitHubUserIssue | ServiceError> {
return await this.executeQuery<GitHubUserIssue>(queryUserIssue, {
username,
}, "userIssue");
}
async requestUserPullRequest(
username: string,
): Promise<GitHubUserPullRequest | ServiceError> {
return await this.executeQuery<GitHubUserPullRequest>(
queryUserPullRequest,
{ username },
"userPullRequest",
);
}
async requestUserInfo(username: string): Promise<UserInfo | ServiceError> {
// Avoid to call others if one of them is null
const repository = await this.requestUserRepository(username);
if (repository === null) {
return new ServiceError("not found", EServiceKindError.NOT_FOUND);
}

const promises = Promise.allSettled([
this.requestUserActivity(username),
this.requestUserIssue(username),
this.requestUserPullRequest(username),
]);
const [activity, issue, pullRequest] = await promises;
const status = [
activity.status,
issue.status,
pullRequest.status,
];

if (status.includes("rejected")) {
console.error(`Can not find a user with username:' ${username}'`);
return new ServiceError("not found", EServiceKindError.NOT_FOUND);
}

return new UserInfo(
(activity as PromiseFulfilledResult<GitHubUserActivity>).value,
(issue as PromiseFulfilledResult<GitHubUserIssue>).value,
(pullRequest as PromiseFulfilledResult<GitHubUserPullRequest>).value,
repository as GitHubUserRepository,
);
}

async executeQuery<T = unknown>(
query: string,
variables: { [key: string]: string },
cache_ns?: string,
) {
const retry = new Retry(
TOKENS.length,
CONSTANTS.DEFAULT_GITHUB_RETRY_DELAY,
);
console.log("HIT");
try {
const response = await retry.fetch<Promise<T>>(async () => {
return await soxa.post("", {}, {
data: { query: query, variables },
headers: {
cache_ns,
"x_api_key": authentication,
},
});
}) as QueryDefaultResponse<{ data: { user: T } }>;

return response?.data?.data?.data?.user ??
new ServiceError("not found", EServiceKindError.NOT_FOUND);
} catch (error) {
// TODO: Move this to a logger instance later
if (error instanceof Error && error.cause) {
console.error(JSON.stringify(error.cause, null, 2));
} else {
console.error(error);
}

return new ServiceError("not found", EServiceKindError.NOT_FOUND);
}
}
}
23 changes: 23 additions & 0 deletions src/Services/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { GithubRepositoryService } from "../Repository/GithubRepository.ts";
import { GithubApiService } from "./GithubApiService.ts";
import { GithubAzureService } from "./GithubAzureService.ts";

export type Provider = GithubApiService | GithubAzureService;

const DEFAULT_PROVIDER = Deno.env.get("provider") ?? "github";

const providers = new Map([
["github", GithubApiService],
["azure", GithubAzureService],
]);

const serviceProvider = providers.get(DEFAULT_PROVIDER);

if (serviceProvider === undefined) {
throw new Error("Invalid provider");
}

const provider = new serviceProvider();
const repositoryClient = new GithubRepositoryService(provider).repository;

export const client = repositoryClient;
4 changes: 2 additions & 2 deletions src/StaticRenderRegeneration/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CacheManager } from "./cache_manager.ts";
import { StaticRegenerationOptions } from "./types.ts";
import { getUrl, hashString, readCache } from "./utils.ts";
import { generateUUID, getUrl, readCache } from "./utils.ts";

export async function staticRenderRegeneration(
request: Request,
Expand All @@ -15,7 +15,7 @@ export async function staticRenderRegeneration(
return await render(request);
}

const cacheFile = await hashString(url.pathname + (url.search ?? ""));
const cacheFile = await generateUUID(url.pathname + (url.search ?? ""));
const cacheManager = new CacheManager(options.revalidate ?? 0, cacheFile);
if (cacheManager.isCacheValid) {
const cache = readCache(cacheManager.cacheFilePath);
Expand Down
2 changes: 1 addition & 1 deletion src/StaticRenderRegeneration/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function readCache(cacheFilePath: string): Uint8Array | null {
}

// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
export async function hashString(message: string): Promise<string> {
export async function generateUUID(message: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
Expand Down

0 comments on commit f3363f1

Please sign in to comment.