chore: types improvements (#226)

chore: types improvements

chore: types improvements
This commit is contained in:
Alexandro Castro 2023-09-30 06:49:18 +01:00 • committed by GitHub
parent 5dc3379214
commit 495eba6a75
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 387 additions and 246 deletions

View file

@ -7,16 +7,21 @@ on:
jobs: jobs:
install-dependencies: install-dependencies:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy:
matrix:
deno-version: [1.36.1]
steps: steps:
- name: Check if PR is in draft mode - name: Git Checkout Deno Module
run: | uses: actions/checkout@v2
if [ "${{ github.event.pull_request.draft }}" == "true" ]; then - name: Use Deno Version ${{ matrix.deno-version }}
echo "PR is in draft mode, skipping workflow"
exit 78
fi
- name: Set up Deno
uses: denolib/setup-deno@v2 uses: denolib/setup-deno@v2
with: with:
deno-version: "1.37.0" deno-version: ${{ matrix.deno-version }}
- name: Run tests - name: Deno format check
run: deno test --allow-env run: deno fmt --check
- name: Deno lint check
run: deno task lint
- name: Test Deno Module
run: deno task test

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
.vscode .vscode
.env .env
.idea .idea
.lock

View file

@ -2,14 +2,14 @@
## Environment ## Environment
* Deno >= v1.9.2 - Deno >= v1.9.2
* [Vercel](https://vercel.com/) - [Vercel](https://vercel.com/)
* GitHub API v4 - GitHub API v4
## Local Run ## Local Run
Create `.env` file to project root directory, and write your GitHub token to the `.env` file. Create `.env` file to project root directory, and write your GitHub token to the
Please select the authority of `repo` when creating token. `.env` file. Please select the authority of `repo` when creating token.
```properties ```properties
GITHUB_TOKEN1=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX GITHUB_TOKEN1=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
@ -23,7 +23,7 @@ GITHUB_API=https://github.example.com/api/graphql
Run local server. Run local server.
```sh ```sh
deno run --allow-net --allow-read --allow-env --allow-write debug.ts deno task start
``` ```
Open localhost from your browser. Open localhost from your browser.
@ -36,7 +36,8 @@ Read the [.editorconfig](./.editorconfig)
## Run deno lint ## Run deno lint
If you want to contribute to my project, you should check the lint with the following command. If you want to contribute to my project, you should check the lint with the
following command.
```sh ```sh
deno lint --unstable deno lint --unstable

View file

@ -34,7 +34,8 @@
# Quick Start # Quick Start
Add the following code to your readme. When pasting the code into your profile's readme, change the `?username=` value to your GitHub's username. Add the following code to your readme. When pasting the code into your profile's
readme, change the `?username=` value to your GitHub's username.
``` ```
[![trophy](https://github-profile-trophy.vercel.app/?username=ryo-ma)](https://github.com/ryo-ma/github-profile-trophy) [![trophy](https://github-profile-trophy.vercel.app/?username=ryo-ma)](https://github.com/ryo-ma/github-profile-trophy)
@ -51,6 +52,7 @@ Add optional parameter of the theme.
``` ```
[![trophy](https://github-profile-trophy.vercel.app/?username=ryo-ma&theme=onedark)](https://github.com/ryo-ma/github-profile-trophy) [![trophy](https://github-profile-trophy.vercel.app/?username=ryo-ma&theme=onedark)](https://github.com/ryo-ma/github-profile-trophy)
``` ```
<p align="center"> <p align="center">
<img width="660" src="https://user-images.githubusercontent.com/6661165/92327052-d99b9e00-f091-11ea-9a24-c7ec86982370.png"> <img width="660" src="https://user-images.githubusercontent.com/6661165/92327052-d99b9e00-f091-11ea-9a24-c7ec86982370.png">
</p> </p>
@ -62,7 +64,7 @@ Add optional parameter of the theme.
Ranks are `SSS` `SS` `S` `AAA` `AA` `A` `B` `C` `UNKNOWN` `SECRET`. Ranks are `SSS` `SS` `S` `AAA` `AA` `A` `B` `C` `UNKNOWN` `SECRET`.
| Rank | Description | | Rank | Description |
| ---- | ---- | | ---------- | ------------------------------------------------------------------------------------------ |
| SSS, SS, S | You are at a hard to reach rank. You can brag. | | SSS, SS, S | You are at a hard to reach rank. You can brag. |
| AAA, AA, A | You will reach this rank if you do your best. Let's aim here first. | | AAA, AA, A | You will reach this rank if you do your best. Let's aim here first. |
| B, C | You are currently making good progress. Let's aim a bit higher. | | B, C | You are currently making good progress. Let's aim a bit higher. |
@ -70,13 +72,16 @@ Ranks are `SSS` `SS` `S` `AAA` `AA` `A` `B` `C` `UNKNOWN` `SECRET`.
| SECRET | This rank is very rare. The trophy will not be displayed until certain conditions are met. | | SECRET | This rank is very rare. The trophy will not be displayed until certain conditions are met. |
## Secret Rank ## Secret Rank
The acquisition condition is secret, but you can know the condition by reading this code.
The acquisition condition is secret, but you can know the condition by reading
this code.
<p align="center"> <p align="center">
<img width="110" src="https://user-images.githubusercontent.com/6661165/91643641-28cd4780-ea70-11ea-94a9-a51885252700.png" /> <img width="110" src="https://user-images.githubusercontent.com/6661165/91643641-28cd4780-ea70-11ea-94a9-a51885252700.png" />
</p> </p>
There are only a few secret trophies. Therefore, if you come up with interesting conditions, I will consider adding a trophy. I am waiting for contributions. There are only a few secret trophies. Therefore, if you come up with interesting
conditions, I will consider adding a trophy. I am waiting for contributions.
# About Display details # About Display details
@ -90,19 +95,17 @@ There are only a few secret trophies. Therefore, if you come up with interesting
4. Target aggregation result. 4. Target aggregation result.
5. Next Rank Bar. The road from the current rank to the next rank. 5. Next Rank Bar. The road from the current rank to the next rank.
# Optional Request Parameters # Optional Request Parameters
* [title](#filter-by-titles) - [title](#filter-by-titles)
* [rank](#filter-by-ranks) - [rank](#filter-by-ranks)
* [column](#specify-the-maximum-row--column-size) - [column](#specify-the-maximum-row--column-size)
* [row](#specify-the-maximum-row--column-size) - [row](#specify-the-maximum-row--column-size)
* [theme](#apply-theme) - [theme](#apply-theme)
* [margin-w](#margin-width) - [margin-w](#margin-width)
* [margin-h](#margin-height) - [margin-h](#margin-height)
* [no-bg](#transparent-background) - [no-bg](#transparent-background)
* [no-frame](#hide-frames) - [no-frame](#hide-frames)
## Filter by titles ## Filter by titles
@ -124,12 +127,13 @@ https://github-profile-trophy.vercel.app/?username=ryo-ma&title=Stars,Followers
## Filter by ranks ## Filter by ranks
You can filter the display by specifying the ranks. You can filter the display by specifying the ranks.\
`Available values: SECRET SSS SS S AAA AA A B C` `Available values: SECRET SSS SS S AAA AA A B C`
``` ```
https://github-profile-trophy.vercel.app/?username=ryo-ma&rank=S https://github-profile-trophy.vercel.app/?username=ryo-ma&rank=S
``` ```
<p align="center"> <p align="center">
<img width="110" src="https://user-images.githubusercontent.com/6661165/91642657-1cdd8780-ea68-11ea-994b-4568a55cd22a.png" /> <img width="110" src="https://user-images.githubusercontent.com/6661165/91642657-1cdd8780-ea68-11ea-994b-4568a55cd22a.png" />
</p> </p>
@ -146,26 +150,28 @@ You can also exclude ranks.
https://github-profile-trophy.vercel.app/?username=ryo-ma&rank=-C,-B https://github-profile-trophy.vercel.app/?username=ryo-ma&rank=-C,-B
``` ```
## Specify the maximum row & column size ## Specify the maximum row & column size
You can specify the maximum row and column size. You can specify the maximum row and column size.\
Trophy will be hidden if it exceeds the range of both row and column. Trophy will be hidden if it exceeds the range of both row and column.
`Available value: number type` `Available value: number type`\
`Default: column=6 row=3` `Default: column=6 row=3`
Restrict only row Restrict only row
``` ```
https://github-profile-trophy.vercel.app/?username=ryo-ma&row=2 https://github-profile-trophy.vercel.app/?username=ryo-ma&row=2
``` ```
Restrict only column Restrict only column
``` ```
https://github-profile-trophy.vercel.app/?username=ryo-ma&column=2 https://github-profile-trophy.vercel.app/?username=ryo-ma&column=2
``` ```
Restrict row & column Restrict row & column
``` ```
https://github-profile-trophy.vercel.app/?username=ryo-ma&row=2&column=3 https://github-profile-trophy.vercel.app/?username=ryo-ma&row=2&column=3
``` ```
@ -175,18 +181,20 @@ https://github-profile-trophy.vercel.app/?username=ryo-ma&row=2&column=3
</p> </p>
Adaptive column Adaptive column
``` ```
https://github-profile-trophy.vercel.app/?username=ryo-ma&column=-1 https://github-profile-trophy.vercel.app/?username=ryo-ma&column=-1
``` ```
You can set `columns` to `-1` to adapt the width to the number of trophies, the parameter `row` will be ignored. You can set `columns` to `-1` to adapt the width to the number of trophies, the
parameter `row` will be ignored.
## Apply theme ## Apply theme
Available themes. Available themes.
| theme | | theme |
| ---- | | --------------------------- |
| [flat](#flat) | | [flat](#flat) |
| [onedark](#onedark) | | [onedark](#onedark) |
| [gruvbox](#gruvbox) | | [gruvbox](#gruvbox) |
@ -210,12 +218,12 @@ Available themes.
| [dark_dimmed](#dark_dimmed) | | [dark_dimmed](#dark_dimmed) |
| [dark_lover](#dark_lover) | | [dark_lover](#dark_lover) |
### flat ### flat
``` ```
https://github-profile-trophy.vercel.app/?username=ryo-ma&theme=flat https://github-profile-trophy.vercel.app/?username=ryo-ma&theme=flat
``` ```
<p align="center"> <p align="center">
<img width="660" src="https://user-images.githubusercontent.com/6661165/92325601-039b9300-f087-11ea-983a-fce8133549ee.png"> <img width="660" src="https://user-images.githubusercontent.com/6661165/92325601-039b9300-f087-11ea-983a-fce8133549ee.png">
</p> </p>
@ -280,7 +288,6 @@ https://github-profile-trophy.vercel.app/?username=ryo-ma&theme=nord
<img width="660" src="https://user-images.githubusercontent.com/6661165/94346857-7ab2be80-006a-11eb-9082-36d377ae2531.png"> <img width="660" src="https://user-images.githubusercontent.com/6661165/94346857-7ab2be80-006a-11eb-9082-36d377ae2531.png">
</p> </p>
### alduin ### alduin
``` ```
@ -433,8 +440,8 @@ https://github-profile-trophy.vercel.app/?username=ryo-ma&theme=dark_lover
## Margin Width ## Margin Width
You can put a margin in the width between trophies. You can put a margin in the width between trophies.\
`Available value: number type` `Available value: number type`\
`Default: margin-w=0` `Default: margin-w=0`
``` ```
@ -447,8 +454,8 @@ https://github-profile-trophy.vercel.app/?username=ryo-ma&margin-w=15
## Margin Height ## Margin Height
You can put a margin in the height between trophies. You can put a margin in the height between trophies.\
`Available value: number type` `Available value: number type`\
`Default: margin-h=0` `Default: margin-h=0`
``` ```
@ -467,8 +474,8 @@ https://github-profile-trophy.vercel.app/?username=ryo-ma&column=3&margin-w=15&m
## Transparent background ## Transparent background
You can turn the background transparent. You can turn the background transparent.\
`Available value: boolean type (true or false)` `Available value: boolean type (true or false)`\
`Default: no-bg=false` `Default: no-bg=false`
``` ```
@ -479,12 +486,10 @@ https://github-profile-trophy.vercel.app/?username=ryo-ma&no-bg=true
<img width=660 src="https://user-images.githubusercontent.com/6661165/104810864-ed72c000-583a-11eb-863b-04acffb705ea.png"> <img width=660 src="https://user-images.githubusercontent.com/6661165/104810864-ed72c000-583a-11eb-863b-04acffb705ea.png">
</p> </p>
## Hide frames ## Hide frames
You can hide the frames around the trophies. You can hide the frames around the trophies.\
`Available value: boolean type (true or false)` `Available value: boolean type (true or false)`\
`Default: no-frame=false` `Default: no-frame=false`
``` ```
@ -495,12 +500,12 @@ https://github-profile-trophy.vercel.app/?username=ryo-ma&no-frame=true
<img width=660 src="https://user-images.githubusercontent.com/6661165/104810887-1d21c800-583b-11eb-8f0d-785c1640dc5d.png"> <img width=660 src="https://user-images.githubusercontent.com/6661165/104810887-1d21c800-583b-11eb-8f0d-785c1640dc5d.png">
</p> </p>
# Contribution Guide # Contribution Guide
Check [CONTRIBUTING.md](./CONTRIBUTING.md) for more details. Check [CONTRIBUTING.md](./CONTRIBUTING.md) for more details.
# Testing # Testing
```bash ```bash
deno test --allow-env deno task test
``` ```

View file

@ -1,11 +1,13 @@
import { Card } from "../src/card.ts"; import { Card } from "../src/card.ts";
import { CONSTANTS, parseParams } from "../src/utils.ts"; import { CONSTANTS, parseParams } from "../src/utils.ts";
import { COLORS, Theme } from "../src/theme.ts"; import { COLORS, Theme } from "../src/theme.ts";
import { Error400, Error404 } from "../src/error_page.ts"; import { Error400 } from "../src/error_page.ts";
import "https://deno.land/x/dotenv@v0.5.0/load.ts"; import "https://deno.land/x/dotenv@v0.5.0/load.ts";
import { staticRenderRegeneration } from "../src/StaticRenderRegeneration/index.ts"; import { staticRenderRegeneration } from "../src/StaticRenderRegeneration/index.ts";
import { GithubRepositoryService } from "../src/Repository/GithubRepository.ts"; import { GithubRepositoryService } from "../src/Repository/GithubRepository.ts";
import { GithubApiService } from "../src/Services/GithubApiService.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 serviceProvider = new GithubApiService();
const client = new GithubRepositoryService(serviceProvider).repository; const client = new GithubRepositoryService(serviceProvider).repository;
@ -74,14 +76,11 @@ async function app(req: Request): Promise<Response> {
); );
} }
const userInfo = await client.requestUserInfo(username); const userInfo = await client.requestUserInfo(username);
if (userInfo === null) { if (userInfo instanceof ServiceError) {
const error = new Error404(
"Can not find a user with username: " + username,
);
return new Response( return new Response(
error.render(), ErrorPage({ error: userInfo, username }).render(),
{ {
status: error.status, status: userInfo.code,
headers: new Headers({ "Content-Type": "text" }), headers: new Headers({ "Content-Type": "text" }),
}, },
); );

9
deno.json Normal file
View file

@ -0,0 +1,9 @@
{
"tasks": {
"start": "deno run -A debug.ts",
"debug": "deno --inspect-brk -A debug.ts",
"format": "deno fmt",
"lint": "deno lint",
"test": "ENV_TYPE=test deno test --allow-env"
}
}

BIN
src/.DS_Store vendored Normal file

Binary file not shown.

19
src/Helpers/Logger.ts Normal file
View file

@ -0,0 +1,19 @@
const enableLogging = Deno.env.get("ENV_TYPE") !== "test";
export class Logger {
public static log(message: unknown): void {
if (!enableLogging) return;
console.log(message);
}
public static error(message: unknown): void {
if (!enableLogging) return;
console.error(message);
}
public static warn(message: unknown): void {
if (!enableLogging) return;
console.warn(message);
}
}

View file

@ -1,3 +1,5 @@
import { Logger } from "./Logger.ts";
export type RetryCallbackProps = { export type RetryCallbackProps = {
attempt: number; attempt: number;
}; };
@ -16,7 +18,7 @@ async function* createAsyncIterable<T>(
return; return;
} catch (e) { } catch (e) {
yield null; yield null;
console.error(e); Logger.error(e);
await new Promise((resolve) => setTimeout(resolve, delay)); await new Promise((resolve) => setTimeout(resolve, delay));
} }
} }

View file

@ -44,7 +44,6 @@ Deno.test("Should retry", async () => {
Deno.test("Should retry the asyncronous callback", async () => { Deno.test("Should retry the asyncronous callback", async () => {
let countErrors = 0; let countErrors = 0;
const callbackError = async () => { const callbackError = async () => {
countErrors++; countErrors++;
// Mock request in callback // Mock request in callback

View file

@ -1,3 +1,4 @@
import { ServiceError } from "../Types/index.ts";
import { import {
GitHubUserActivity, GitHubUserActivity,
GitHubUserIssue, GitHubUserIssue,
@ -7,17 +8,19 @@ import {
} from "../user_info.ts"; } from "../user_info.ts";
export abstract class GithubRepository { export abstract class GithubRepository {
abstract requestUserInfo(username: string): Promise<UserInfo | null>; abstract requestUserInfo(username: string): Promise<UserInfo | ServiceError>;
abstract requestUserActivity( abstract requestUserActivity(
username: string, username: string,
): Promise<GitHubUserActivity | null>; ): Promise<GitHubUserActivity | ServiceError>;
abstract requestUserIssue(username: string): Promise<GitHubUserIssue | null>; abstract requestUserIssue(
username: string,
): Promise<GitHubUserIssue | ServiceError>;
abstract requestUserPullRequest( abstract requestUserPullRequest(
username: string, username: string,
): Promise<GitHubUserPullRequest | null>; ): Promise<GitHubUserPullRequest | ServiceError>;
abstract requestUserRepository( abstract requestUserRepository(
username: string, username: string,
): Promise<GitHubUserRepository | null>; ): Promise<GitHubUserRepository | ServiceError>;
} }
export class GithubRepositoryService { export class GithubRepositoryService {

View file

@ -14,8 +14,11 @@ import {
} from "../Schemas/index.ts"; } from "../Schemas/index.ts";
import { soxa } from "../../deps.ts"; import { soxa } from "../../deps.ts";
import { Retry } from "../Helpers/Retry.ts"; import { Retry } from "../Helpers/Retry.ts";
import { QueryDefaultResponse } from "../Types/index.ts"; import { GithubError, QueryDefaultResponse } from "../Types/index.ts";
import { CONSTANTS } from "../utils.ts"; import { CONSTANTS } from "../utils.ts";
import { EServiceKindError } from "../Types/EServiceKindError.ts";
import { ServiceError } from "../Types/ServiceError.ts";
import { Logger } from "../Helpers/Logger.ts";
// Need to be here - Exporting from another file makes array of null // Need to be here - Exporting from another file makes array of null
export const TOKENS = [ export const TOKENS = [
@ -26,35 +29,40 @@ export const TOKENS = [
export class GithubApiService extends GithubRepository { export class GithubApiService extends GithubRepository {
async requestUserRepository( async requestUserRepository(
username: string, username: string,
): Promise<GitHubUserRepository | null> { ): Promise<GitHubUserRepository | ServiceError> {
return await this.executeQuery<GitHubUserRepository>(queryUserRepository, { return await this.executeQuery<GitHubUserRepository>(queryUserRepository, {
username, username,
}); });
} }
async requestUserActivity( async requestUserActivity(
username: string, username: string,
): Promise<GitHubUserActivity | null> { ): Promise<GitHubUserActivity | ServiceError> {
return await this.executeQuery<GitHubUserActivity>(queryUserActivity, { return await this.executeQuery<GitHubUserActivity>(queryUserActivity, {
username, username,
}); });
} }
async requestUserIssue(username: string): Promise<GitHubUserIssue | null> { async requestUserIssue(
username: string,
): Promise<GitHubUserIssue | ServiceError> {
return await this.executeQuery<GitHubUserIssue>(queryUserIssue, { return await this.executeQuery<GitHubUserIssue>(queryUserIssue, {
username, username,
}); });
} }
async requestUserPullRequest( async requestUserPullRequest(
username: string, username: string,
): Promise<GitHubUserPullRequest | null> { ): Promise<GitHubUserPullRequest | ServiceError> {
return await this.executeQuery<GitHubUserPullRequest>( return await this.executeQuery<GitHubUserPullRequest>(
queryUserPullRequest, queryUserPullRequest,
{ username }, { username },
); );
} }
async requestUserInfo(username: string): Promise<UserInfo | null> { async requestUserInfo(username: string): Promise<UserInfo | ServiceError> {
// Avoid to call others if one of them is null // Avoid to call others if one of them is null
const repository = await this.requestUserRepository(username); const repository = await this.requestUserRepository(username);
if (repository === null) return null; if (repository instanceof ServiceError) {
Logger.error(repository);
return repository;
}
const promises = Promise.allSettled([ const promises = Promise.allSettled([
this.requestUserActivity(username), this.requestUserActivity(username),
@ -69,15 +77,34 @@ export class GithubApiService extends GithubRepository {
]; ];
if (status.includes("rejected")) { if (status.includes("rejected")) {
console.error(`Can not find a user with username:' ${username}'`); Logger.error(`Can not find a user with username:' ${username}'`);
return null; return new ServiceError("not found", EServiceKindError.NOT_FOUND);
} }
return new UserInfo( return new UserInfo(
(activity as PromiseFulfilledResult<GitHubUserActivity>).value, (activity as PromiseFulfilledResult<GitHubUserActivity>).value,
(issue as PromiseFulfilledResult<GitHubUserIssue>).value, (issue as PromiseFulfilledResult<GitHubUserIssue>).value,
(pullRequest as PromiseFulfilledResult<GitHubUserPullRequest>).value, (pullRequest as PromiseFulfilledResult<GitHubUserPullRequest>).value,
repository, repository as GitHubUserRepository,
);
}
private handleError(responseErrors: GithubError[]): ServiceError {
const errors = responseErrors ?? [];
const isRateLimitExceeded = (errors ?? []).some((error) => {
error.type.includes(EServiceKindError.RATE_LIMIT);
});
if (isRateLimitExceeded) {
throw new ServiceError(
"Rate limit exceeded",
EServiceKindError.RATE_LIMIT,
);
}
throw new ServiceError(
"unknown error",
EServiceKindError.NOT_FOUND,
); );
} }
@ -97,24 +124,23 @@ export class GithubApiService extends GithubRepository {
Authorization: `bearer ${TOKENS[attempt]}`, Authorization: `bearer ${TOKENS[attempt]}`,
}, },
}); });
}) as QueryDefaultResponse<{ user: T; errors?: unknown[] }>; }) as QueryDefaultResponse<{ user: T }>;
if (response.data.data.errors) { if (response?.data?.errors) {
throw new Error("Error from Github API", { return this.handleError(response?.data?.errors);
cause: response.data.data.errors,
});
} }
return response?.data?.data?.user ?? null; return response?.data?.data?.user ??
new ServiceError("not found", EServiceKindError.NOT_FOUND);
} catch (error) { } catch (error) {
// TODO: Move this to a logger instance later // TODO: Move this to a logger instance later
if (error instanceof Error && error.cause) { if (error instanceof Error && error.cause) {
console.error(JSON.stringify(error.cause, null, 2)); Logger.error(JSON.stringify(error.cause, null, 2));
} else { } else {
console.error(error); Logger.error(error);
} }
return null; return new ServiceError("not found", EServiceKindError.NOT_FOUND);
} }
} }
} }

View file

@ -1,3 +1,4 @@
import { Logger } from "../Helpers/Logger.ts";
import { existsSync } from "./utils.ts"; import { existsSync } from "./utils.ts";
export class CacheManager { export class CacheManager {
@ -44,7 +45,7 @@ export class CacheManager {
const data = new TextEncoder().encode(text); const data = new TextEncoder().encode(text);
Deno.writeFile(this.cacheFilePath, data, { create: true }).catch(() => { Deno.writeFile(this.cacheFilePath, data, { create: true }).catch(() => {
console.warn("Failed to save cache file"); Logger.warn("Failed to save cache file");
}); });
} }
} }

View file

@ -1,20 +1,24 @@
import { CacheManager } from "./cache_manager.ts"; import { CacheManager } from "./cache_manager.ts";
import { StaticRegenerationOptions } from "./types.ts"; import { StaticRegenerationOptions } from "./types.ts";
import { getUrl, readCache, generateUUID } from "./utils.ts"; import { getUrl, hashString, readCache } from "./utils.ts";
export async function staticRenderRegeneration(request: Request, options: StaticRegenerationOptions, render: (request: Request) => Promise<Response>) { export async function staticRenderRegeneration(
request: Request,
options: StaticRegenerationOptions,
render: (request: Request) => Promise<Response>,
) {
// avoid TypeError: Invalid URL at deno:core // avoid TypeError: Invalid URL at deno:core
const url = getUrl(request) const url = getUrl(request);
// if more conditions are added, make sure to create a variable to skipCache // if more conditions are added, make sure to create a variable to skipCache
if (url.pathname === "/favicon.ico") { if (url.pathname === "/favicon.ico") {
return await render(request); return await render(request);
} }
const cacheFile = await generateUUID(url.pathname + (url.search ?? "")); const cacheFile = await hashString(url.pathname + (url.search ?? ""));
const cacheManager = new CacheManager(options.revalidate ?? 0, cacheFile); const cacheManager = new CacheManager(options.revalidate ?? 0, cacheFile);
if (cacheManager.isCacheValid) { if (cacheManager.isCacheValid) {
const cache = readCache(cacheManager.cacheFilePath) const cache = readCache(cacheManager.cacheFilePath);
if (cache !== null) { if (cache !== null) {
return new Response(cache, { return new Response(cache, {
headers: options.headers ?? new Headers({}), headers: options.headers ?? new Headers({}),
@ -22,8 +26,11 @@ export async function staticRenderRegeneration(request: Request, options: Static
} }
} }
const response = await render(request) const response = await render(request);
cacheManager.save(response)
return response if (response.status >= 200 && response.status < 300) {
cacheManager.save(response);
}
return response;
} }

View file

@ -1,6 +1,6 @@
export interface StaticRegenerationOptions { export interface StaticRegenerationOptions {
// The number of milliseconds before the page should be revalidated // The number of milliseconds before the page should be revalidated
revalidate?: number revalidate?: number;
// The headers to be sent with the response // The headers to be sent with the response
headers?: Headers headers?: Headers;
} }

View file

@ -1,35 +1,36 @@
export function getUrl(request: Request) { export function getUrl(request: Request) {
try { try {
return new URL(request.url) return new URL(request.url);
} catch { } catch {
return { return {
pathname: request.url, pathname: request.url,
search: request.url search: request.url,
} };
} }
} }
export function readCache(cacheFilePath: string): Uint8Array | null { export function readCache(cacheFilePath: string): Uint8Array | null {
try { try {
return Deno.readFileSync(cacheFilePath) return Deno.readFileSync(cacheFilePath);
} catch { } catch {
return null return null;
} }
} }
// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
export async function generateUUID(message: string): Promise<string> { export async function hashString(message: string): Promise<string> {
const encoder = new TextEncoder(); const encoder = new TextEncoder();
const data = encoder.encode(message); const data = encoder.encode(message);
const hashBuffer = await crypto.subtle.digest("SHA-256", data); const hashBuffer = await crypto.subtle.digest("SHA-256", data);
const hashArray = Array.from(new Uint8Array(hashBuffer)); const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(
"",
);
return hashHex; return hashHex;
} }
export const existsSync = (filename: string): boolean => { export const existsSync = (filename: string): boolean => {
try { try {
Deno.statSync(filename); Deno.statSync(filename);
@ -39,4 +40,3 @@ export const existsSync = (filename: string): boolean => {
return false; return false;
} }
}; };

View file

@ -0,0 +1,4 @@
export const enum EServiceKindError {
RATE_LIMIT = "RATE_LIMITED",
NOT_FOUND = "NOT_FOUND",
}

View file

@ -1,5 +1,11 @@
export type GithubError = {
message: string;
type: string;
};
export type QueryDefaultResponse<T = unknown> = { export type QueryDefaultResponse<T = unknown> = {
data: { data: {
data: T; data: T;
errors: GithubError[];
}; };
}; };

20
src/Types/ServiceError.ts Normal file
View file

@ -0,0 +1,20 @@
import { EServiceKindError } from "./EServiceKindError.ts";
export class ServiceError extends Error {
constructor(message: string, kind: EServiceKindError) {
super(message);
this.name = "ServiceError";
this.cause = kind;
}
get code(): number {
switch (this.cause) {
case EServiceKindError.RATE_LIMIT:
return 419;
case EServiceKindError.NOT_FOUND:
return 404;
default:
return 400;
}
}
}

View file

@ -1 +1,3 @@
export * from './Request.ts' export * from "./Request.ts";
export * from "./ServiceError.ts";
export * from "./EServiceKindError.ts";

View file

@ -14,6 +14,11 @@ export class Error400 extends BaseError {
readonly message = "Bad Request"; readonly message = "Bad Request";
} }
export class Error419 extends BaseError {
readonly status = 419;
readonly message = "Rate Limit Exceeded";
}
export class Error404 extends BaseError { export class Error404 extends BaseError {
readonly status = 404; readonly status = 404;
readonly message = "Not Found"; readonly message = "Not Found";

23
src/pages/Error.ts Normal file
View file

@ -0,0 +1,23 @@
import { EServiceKindError, ServiceError } from "../Types/index.ts";
import { Error400, Error404, Error419 } from "../error_page.ts";
interface ErrorPageProps {
error: ServiceError;
username: string;
}
export function ErrorPage({ error, username }: ErrorPageProps) {
let cause: Error400 | Error404 | Error419 = new Error400();
if (error.cause === EServiceKindError.RATE_LIMIT) {
cause = new Error419();
}
if (error.cause === EServiceKindError.NOT_FOUND) {
cause = new Error404(
"Can not find a user with username: " + username,
);
}
return cause;
}

View file

@ -550,7 +550,7 @@ export const COLORS: {[name: string]: Theme} = {
DEFAULT_RANK_BASE: "#7f6ceb", DEFAULT_RANK_BASE: "#7f6ceb",
DEFAULT_RANK_SHADOW: "#a598ed", DEFAULT_RANK_SHADOW: "#a598ed",
DEFAULT_RANK_TEXT: "#7f6ceb", DEFAULT_RANK_TEXT: "#7f6ceb",
} },
}; };
export interface Theme { export interface Theme {
@ -577,4 +577,3 @@ export interface Theme {
DEFAULT_RANK_SHADOW: string; DEFAULT_RANK_SHADOW: string;
DEFAULT_RANK_TEXT: string; DEFAULT_RANK_TEXT: string;
} }

View file

@ -1,5 +1,5 @@
import { getTrophyIcon, getNextRankBar } from "./icons.ts"; import { getNextRankBar, getTrophyIcon } from "./icons.ts";
import { CONSTANTS, RANK, abridgeScore, RANK_ORDER } from "./utils.ts"; import { abridgeScore, CONSTANTS, RANK, RANK_ORDER } from "./utils.ts";
import { Theme } from "./theme.ts"; import { Theme } from "./theme.ts";
class RankCondition { class RankCondition {
@ -10,7 +10,6 @@ class RankCondition {
) {} ) {}
} }
export class Trophy { export class Trophy {
rankCondition: RankCondition | null = null; rankCondition: RankCondition | null = null;
rank: RANK = RANK.UNKNOWN; rank: RANK = RANK.UNKNOWN;
@ -59,14 +58,16 @@ export class Trophy {
const result = progress / distance; const result = progress / distance;
return result; return result;
} }
render(theme: Theme, render(
theme: Theme,
x = 0, x = 0,
y = 0, y = 0,
panelSize = CONSTANTS.DEFAULT_PANEL_SIZE, panelSize = CONSTANTS.DEFAULT_PANEL_SIZE,
noBackground = CONSTANTS.DEFAULT_NO_BACKGROUND, noBackground = CONSTANTS.DEFAULT_NO_BACKGROUND,
noFrame = CONSTANTS.DEFAULT_NO_FRAME, noFrame = CONSTANTS.DEFAULT_NO_FRAME,
): string { ): string {
const { BACKGROUND: PRIMARY, TITLE: SECONDARY, TEXT, NEXT_RANK_BAR } = theme; const { BACKGROUND: PRIMARY, TITLE: SECONDARY, TEXT, NEXT_RANK_BAR } =
theme;
const nextRankBar = getNextRankBar( const nextRankBar = getNextRankBar(
this.title, this.title,
this.calculateNextRankPercentage(), this.calculateNextRankPercentage(),
@ -90,8 +91,8 @@ export class Trophy {
height="${panelSize - 1}" height="${panelSize - 1}"
stroke="#e1e4e8" stroke="#e1e4e8"
fill="${PRIMARY}" fill="${PRIMARY}"
stroke-opacity="${noFrame ? '0' : '1'}" stroke-opacity="${noFrame ? "0" : "1"}"
fill-opacity="${noBackground ? '0' : '1'}" fill-opacity="${noBackground ? "0" : "1"}"
/> />
${getTrophyIcon(theme, this.rank)} ${getTrophyIcon(theme, this.rank)}
<text x="50%" y="18" text-anchor="middle" font-family="Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji" font-weight="bold" font-size="13" fill="${SECONDARY}">${this.title}</text> <text x="50%" y="18" text-anchor="middle" font-family="Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji" font-weight="bold" font-size="13" fill="${SECONDARY}">${this.title}</text>
@ -131,7 +132,7 @@ export class AllSuperRankTrophy extends Trophy{
super(score, rankConditions); super(score, rankConditions);
this.title = "AllSuperRank"; this.title = "AllSuperRank";
this.filterTitles = ["AllSuperRank"]; this.filterTitles = ["AllSuperRank"];
this.bottomMessage = "All S Rank" this.bottomMessage = "All S Rank";
this.hidden = true; this.hidden = true;
} }
} }
@ -147,7 +148,7 @@ export class Joined2020Trophy extends Trophy{
super(score, rankConditions); super(score, rankConditions);
this.title = "Joined2020"; this.title = "Joined2020";
this.filterTitles = ["Joined2020"]; this.filterTitles = ["Joined2020"];
this.bottomMessage = "Joined 2020" this.bottomMessage = "Joined 2020";
this.hidden = true; this.hidden = true;
} }
} }
@ -163,7 +164,7 @@ export class AncientAccountTrophy extends Trophy{
super(score, rankConditions); super(score, rankConditions);
this.title = "AncientUser"; this.title = "AncientUser";
this.filterTitles = ["AncientUser"]; this.filterTitles = ["AncientUser"];
this.bottomMessage = "Before 2010" this.bottomMessage = "Before 2010";
this.hidden = true; this.hidden = true;
} }
} }
@ -211,7 +212,7 @@ export class OGAccountTrophy extends Trophy{
super(score, rankConditions); super(score, rankConditions);
this.title = "OGUser"; this.title = "OGUser";
this.filterTitles = ["OGUser"]; this.filterTitles = ["OGUser"];
this.bottomMessage = "Joined 2008" this.bottomMessage = "Joined 2008";
this.hidden = true; this.hidden = true;
} }
} }

View file

@ -1,22 +1,22 @@
import { import {
Trophy, AllSuperRankTrophy,
TotalStarTrophy, AncientAccountTrophy,
Joined2020Trophy,
LongTimeAccountTrophy,
MultipleLangTrophy,
MultipleOrganizationsTrophy,
OGAccountTrophy,
TotalCommitTrophy, TotalCommitTrophy,
TotalFollowerTrophy, TotalFollowerTrophy,
TotalIssueTrophy, TotalIssueTrophy,
TotalPullRequestTrophy, TotalPullRequestTrophy,
TotalRepositoryTrophy, TotalRepositoryTrophy,
TotalReviewsTrophy, TotalReviewsTrophy,
MultipleLangTrophy, TotalStarTrophy,
LongTimeAccountTrophy, Trophy,
AncientAccountTrophy,
OGAccountTrophy,
Joined2020Trophy,
AllSuperRankTrophy,
MultipleOrganizationsTrophy,
} from "./trophy.ts"; } from "./trophy.ts";
import { UserInfo } from "./user_info.ts"; import { UserInfo } from "./user_info.ts";
import { RANK_ORDER, RANK } from "./utils.ts"; import { RANK, RANK_ORDER } from "./utils.ts";
export class TrophyList { export class TrophyList {
private trophies = new Array<Trophy>(); private trophies = new Array<Trophy>();
@ -49,7 +49,9 @@ export class TrophyList {
return this.trophies; return this.trophies;
} }
private get isAllSRank() { private get isAllSRank() {
return this.trophies.every((trophy) => trophy.rank.slice(0, 1) == RANK.S) ? 1 : 0; return this.trophies.every((trophy) => trophy.rank.slice(0, 1) == RANK.S)
? 1
: 0;
} }
filterByHideen() { filterByHideen() {
this.trophies = this.trophies.filter((trophy) => this.trophies = this.trophies.filter((trophy) =>
@ -64,9 +66,9 @@ export class TrophyList {
filterByRanks(ranks: Array<string>) { filterByRanks(ranks: Array<string>) {
if (ranks.filter((rank) => rank.includes("-")).length !== 0) { if (ranks.filter((rank) => rank.includes("-")).length !== 0) {
this.trophies = this.trophies.filter((trophy) => this.trophies = this.trophies.filter((trophy) =>
!ranks.map(rank => rank.substring(1)).includes(trophy.rank) !ranks.map((rank) => rank.substring(1)).includes(trophy.rank)
) );
return return;
} }
this.trophies = this.trophies.filter((trophy) => this.trophies = this.trophies.filter((trophy) =>
ranks.includes(trophy.rank) ranks.includes(trophy.rank)
@ -78,4 +80,3 @@ export class TrophyList {
); );
} }
} }

View file

@ -88,15 +88,18 @@ export class UserInfo {
const joined2020 = new Date(userActivity.createdAt).getFullYear() == 2020 const joined2020 = new Date(userActivity.createdAt).getFullYear() == 2020
? 1 ? 1
: 0; : 0;
const ogAccount = const ogAccount = new Date(userActivity.createdAt).getFullYear() <= 2008
new Date(userActivity.createdAt).getFullYear() <= 2008 ? 1 : 0; ? 1
: 0;
this.totalCommits = totalCommits; this.totalCommits = totalCommits;
this.totalFollowers = userActivity.followers.totalCount; this.totalFollowers = userActivity.followers.totalCount;
this.totalIssues = userIssue.openIssues.totalCount + userIssue.closedIssues.totalCount; this.totalIssues = userIssue.openIssues.totalCount +
userIssue.closedIssues.totalCount;
this.totalOrganizations = userActivity.organizations.totalCount; this.totalOrganizations = userActivity.organizations.totalCount;
this.totalPullRequests = userPullRequest.pullRequests.totalCount; this.totalPullRequests = userPullRequest.pullRequests.totalCount;
this.totalReviews = userActivity.contributionsCollection.totalPullRequestReviewContributions; this.totalReviews =
userActivity.contributionsCollection.totalPullRequestReviewContributions;
this.totalStargazers = totalStargazers; this.totalStargazers = totalStargazers;
this.totalRepositories = userRepository.repositories.totalCount; this.totalRepositories = userRepository.repositories.totalCount;
this.languageCount = languages.size; this.languageCount = languages.size;