mirror of
https://github.com/reiyua/github-profile-trophy-reiyua-mirror.git
synced 2026-11-17 06:02:09 +11:00
chore: types improvements (#226)
chore: types improvements chore: types improvements
This commit is contained in:
parent
5dc3379214
commit
495eba6a75
28 changed files with 387 additions and 246 deletions
25
.github/workflows/testing.yml
vendored
25
.github/workflows/testing.yml
vendored
|
|
@ -7,16 +7,21 @@ on:
|
|||
jobs:
|
||||
install-dependencies:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
deno-version: [1.36.1]
|
||||
|
||||
steps:
|
||||
- name: Check if PR is in draft mode
|
||||
run: |
|
||||
if [ "${{ github.event.pull_request.draft }}" == "true" ]; then
|
||||
echo "PR is in draft mode, skipping workflow"
|
||||
exit 78
|
||||
fi
|
||||
- name: Set up Deno
|
||||
- name: Git Checkout Deno Module
|
||||
uses: actions/checkout@v2
|
||||
- name: Use Deno Version ${{ matrix.deno-version }}
|
||||
uses: denolib/setup-deno@v2
|
||||
with:
|
||||
deno-version: "1.37.0"
|
||||
- name: Run tests
|
||||
run: deno test --allow-env
|
||||
deno-version: ${{ matrix.deno-version }}
|
||||
- name: Deno format check
|
||||
run: deno fmt --check
|
||||
- name: Deno lint check
|
||||
run: deno task lint
|
||||
- name: Test Deno Module
|
||||
run: deno task test
|
||||
|
|
|
|||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1,3 +1,4 @@
|
|||
.vscode
|
||||
.env
|
||||
.idea
|
||||
.lock
|
||||
|
|
|
|||
|
|
@ -2,14 +2,14 @@
|
|||
|
||||
## Environment
|
||||
|
||||
* Deno >= v1.9.2
|
||||
* [Vercel](https://vercel.com/)
|
||||
* GitHub API v4
|
||||
- Deno >= v1.9.2
|
||||
- [Vercel](https://vercel.com/)
|
||||
- GitHub API v4
|
||||
|
||||
## Local Run
|
||||
|
||||
Create `.env` file to project root directory, and write your GitHub token to the `.env` file.
|
||||
Please select the authority of `repo` when creating token.
|
||||
Create `.env` file to project root directory, and write your GitHub token to the
|
||||
`.env` file. Please select the authority of `repo` when creating token.
|
||||
|
||||
```properties
|
||||
GITHUB_TOKEN1=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||
|
|
@ -23,7 +23,7 @@ GITHUB_API=https://github.example.com/api/graphql
|
|||
Run local server.
|
||||
|
||||
```sh
|
||||
deno run --allow-net --allow-read --allow-env --allow-write debug.ts
|
||||
deno task start
|
||||
```
|
||||
|
||||
Open localhost from your browser.
|
||||
|
|
@ -36,7 +36,8 @@ Read the [.editorconfig](./.editorconfig)
|
|||
|
||||
## 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
|
||||
deno lint --unstable
|
||||
|
|
|
|||
75
README.md
75
README.md
|
|
@ -34,7 +34,8 @@
|
|||
|
||||
# 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.
|
||||
|
||||
```
|
||||
[](https://github.com/ryo-ma/github-profile-trophy)
|
||||
|
|
@ -51,6 +52,7 @@ Add optional parameter of the theme.
|
|||
```
|
||||
[](https://github.com/ryo-ma/github-profile-trophy)
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<img width="660" src="https://user-images.githubusercontent.com/6661165/92327052-d99b9e00-f091-11ea-9a24-c7ec86982370.png">
|
||||
</p>
|
||||
|
|
@ -62,7 +64,7 @@ Add optional parameter of the theme.
|
|||
Ranks are `SSS` `SS` `S` `AAA` `AA` `A` `B` `C` `UNKNOWN` `SECRET`.
|
||||
|
||||
| Rank | Description |
|
||||
| ---- | ---- |
|
||||
| ---------- | ------------------------------------------------------------------------------------------ |
|
||||
| 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. |
|
||||
| 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 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">
|
||||
<img width="110" src="https://user-images.githubusercontent.com/6661165/91643641-28cd4780-ea70-11ea-94a9-a51885252700.png" />
|
||||
</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
|
||||
|
||||
|
|
@ -90,19 +95,17 @@ There are only a few secret trophies. Therefore, if you come up with interesting
|
|||
4. Target aggregation result.
|
||||
5. Next Rank Bar. The road from the current rank to the next rank.
|
||||
|
||||
|
||||
# Optional Request Parameters
|
||||
|
||||
* [title](#filter-by-titles)
|
||||
* [rank](#filter-by-ranks)
|
||||
* [column](#specify-the-maximum-row--column-size)
|
||||
* [row](#specify-the-maximum-row--column-size)
|
||||
* [theme](#apply-theme)
|
||||
* [margin-w](#margin-width)
|
||||
* [margin-h](#margin-height)
|
||||
* [no-bg](#transparent-background)
|
||||
* [no-frame](#hide-frames)
|
||||
|
||||
- [title](#filter-by-titles)
|
||||
- [rank](#filter-by-ranks)
|
||||
- [column](#specify-the-maximum-row--column-size)
|
||||
- [row](#specify-the-maximum-row--column-size)
|
||||
- [theme](#apply-theme)
|
||||
- [margin-w](#margin-width)
|
||||
- [margin-h](#margin-height)
|
||||
- [no-bg](#transparent-background)
|
||||
- [no-frame](#hide-frames)
|
||||
|
||||
## Filter by titles
|
||||
|
||||
|
|
@ -124,12 +127,13 @@ https://github-profile-trophy.vercel.app/?username=ryo-ma&title=Stars,Followers
|
|||
|
||||
## 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`
|
||||
|
||||
```
|
||||
https://github-profile-trophy.vercel.app/?username=ryo-ma&rank=S
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<img width="110" src="https://user-images.githubusercontent.com/6661165/91642657-1cdd8780-ea68-11ea-994b-4568a55cd22a.png" />
|
||||
</p>
|
||||
|
|
@ -146,26 +150,28 @@ You can also exclude ranks.
|
|||
https://github-profile-trophy.vercel.app/?username=ryo-ma&rank=-C,-B
|
||||
```
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
`Available value: number type`
|
||||
`Available value: number type`\
|
||||
`Default: column=6 row=3`
|
||||
|
||||
Restrict only row
|
||||
|
||||
```
|
||||
https://github-profile-trophy.vercel.app/?username=ryo-ma&row=2
|
||||
```
|
||||
|
||||
Restrict only column
|
||||
|
||||
```
|
||||
https://github-profile-trophy.vercel.app/?username=ryo-ma&column=2
|
||||
```
|
||||
|
||||
Restrict row & column
|
||||
|
||||
```
|
||||
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>
|
||||
|
||||
Adaptive column
|
||||
|
||||
```
|
||||
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
|
||||
|
||||
Available themes.
|
||||
|
||||
| theme |
|
||||
| ---- |
|
||||
| --------------------------- |
|
||||
| [flat](#flat) |
|
||||
| [onedark](#onedark) |
|
||||
| [gruvbox](#gruvbox) |
|
||||
|
|
@ -210,12 +218,12 @@ Available themes.
|
|||
| [dark_dimmed](#dark_dimmed) |
|
||||
| [dark_lover](#dark_lover) |
|
||||
|
||||
|
||||
### flat
|
||||
|
||||
```
|
||||
https://github-profile-trophy.vercel.app/?username=ryo-ma&theme=flat
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<img width="660" src="https://user-images.githubusercontent.com/6661165/92325601-039b9300-f087-11ea-983a-fce8133549ee.png">
|
||||
</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">
|
||||
</p>
|
||||
|
||||
|
||||
### alduin
|
||||
|
||||
```
|
||||
|
|
@ -433,8 +440,8 @@ https://github-profile-trophy.vercel.app/?username=ryo-ma&theme=dark_lover
|
|||
|
||||
## Margin Width
|
||||
|
||||
You can put a margin in the width between trophies.
|
||||
`Available value: number type`
|
||||
You can put a margin in the width between trophies.\
|
||||
`Available value: number type`\
|
||||
`Default: margin-w=0`
|
||||
|
||||
```
|
||||
|
|
@ -447,8 +454,8 @@ https://github-profile-trophy.vercel.app/?username=ryo-ma&margin-w=15
|
|||
|
||||
## Margin Height
|
||||
|
||||
You can put a margin in the height between trophies.
|
||||
`Available value: number type`
|
||||
You can put a margin in the height between trophies.\
|
||||
`Available value: number type`\
|
||||
`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
|
||||
|
||||
You can turn the background transparent.
|
||||
`Available value: boolean type (true or false)`
|
||||
You can turn the background transparent.\
|
||||
`Available value: boolean type (true or 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">
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
## Hide frames
|
||||
|
||||
You can hide the frames around the trophies.
|
||||
`Available value: boolean type (true or false)`
|
||||
You can hide the frames around the trophies.\
|
||||
`Available value: boolean type (true or 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">
|
||||
</p>
|
||||
|
||||
|
||||
# Contribution Guide
|
||||
|
||||
Check [CONTRIBUTING.md](./CONTRIBUTING.md) for more details.
|
||||
|
||||
# Testing
|
||||
|
||||
```bash
|
||||
deno test --allow-env
|
||||
deno task test
|
||||
```
|
||||
|
|
|
|||
13
api/index.ts
13
api/index.ts
|
|
@ -1,11 +1,13 @@
|
|||
import { Card } from "../src/card.ts";
|
||||
import { CONSTANTS, parseParams } from "../src/utils.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 { 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;
|
||||
|
|
@ -74,14 +76,11 @@ async function app(req: Request): Promise<Response> {
|
|||
);
|
||||
}
|
||||
const userInfo = await client.requestUserInfo(username);
|
||||
if (userInfo === null) {
|
||||
const error = new Error404(
|
||||
"Can not find a user with username: " + username,
|
||||
);
|
||||
if (userInfo instanceof ServiceError) {
|
||||
return new Response(
|
||||
error.render(),
|
||||
ErrorPage({ error: userInfo, username }).render(),
|
||||
{
|
||||
status: error.status,
|
||||
status: userInfo.code,
|
||||
headers: new Headers({ "Content-Type": "text" }),
|
||||
},
|
||||
);
|
||||
|
|
|
|||
9
deno.json
Normal file
9
deno.json
Normal 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
BIN
src/.DS_Store
vendored
Normal file
Binary file not shown.
19
src/Helpers/Logger.ts
Normal file
19
src/Helpers/Logger.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
import { Logger } from "./Logger.ts";
|
||||
|
||||
export type RetryCallbackProps = {
|
||||
attempt: number;
|
||||
};
|
||||
|
|
@ -16,7 +18,7 @@ async function* createAsyncIterable<T>(
|
|||
return;
|
||||
} catch (e) {
|
||||
yield null;
|
||||
console.error(e);
|
||||
Logger.error(e);
|
||||
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,7 +44,6 @@ Deno.test("Should retry", async () => {
|
|||
|
||||
Deno.test("Should retry the asyncronous callback", async () => {
|
||||
let countErrors = 0;
|
||||
|
||||
const callbackError = async () => {
|
||||
countErrors++;
|
||||
// Mock request in callback
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { ServiceError } from "../Types/index.ts";
|
||||
import {
|
||||
GitHubUserActivity,
|
||||
GitHubUserIssue,
|
||||
|
|
@ -7,17 +8,19 @@ import {
|
|||
} from "../user_info.ts";
|
||||
|
||||
export abstract class GithubRepository {
|
||||
abstract requestUserInfo(username: string): Promise<UserInfo | null>;
|
||||
abstract requestUserInfo(username: string): Promise<UserInfo | ServiceError>;
|
||||
abstract requestUserActivity(
|
||||
username: string,
|
||||
): Promise<GitHubUserActivity | null>;
|
||||
abstract requestUserIssue(username: string): Promise<GitHubUserIssue | null>;
|
||||
): Promise<GitHubUserActivity | ServiceError>;
|
||||
abstract requestUserIssue(
|
||||
username: string,
|
||||
): Promise<GitHubUserIssue | ServiceError>;
|
||||
abstract requestUserPullRequest(
|
||||
username: string,
|
||||
): Promise<GitHubUserPullRequest | null>;
|
||||
): Promise<GitHubUserPullRequest | ServiceError>;
|
||||
abstract requestUserRepository(
|
||||
username: string,
|
||||
): Promise<GitHubUserRepository | null>;
|
||||
): Promise<GitHubUserRepository | ServiceError>;
|
||||
}
|
||||
|
||||
export class GithubRepositoryService {
|
||||
|
|
|
|||
|
|
@ -14,8 +14,11 @@ import {
|
|||
} from "../Schemas/index.ts";
|
||||
import { soxa } from "../../deps.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 { 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
|
||||
export const TOKENS = [
|
||||
|
|
@ -26,35 +29,40 @@ export const TOKENS = [
|
|||
export class GithubApiService extends GithubRepository {
|
||||
async requestUserRepository(
|
||||
username: string,
|
||||
): Promise<GitHubUserRepository | null> {
|
||||
): Promise<GitHubUserRepository | ServiceError> {
|
||||
return await this.executeQuery<GitHubUserRepository>(queryUserRepository, {
|
||||
username,
|
||||
});
|
||||
}
|
||||
async requestUserActivity(
|
||||
username: string,
|
||||
): Promise<GitHubUserActivity | null> {
|
||||
): Promise<GitHubUserActivity | ServiceError> {
|
||||
return await this.executeQuery<GitHubUserActivity>(queryUserActivity, {
|
||||
username,
|
||||
});
|
||||
}
|
||||
async requestUserIssue(username: string): Promise<GitHubUserIssue | null> {
|
||||
async requestUserIssue(
|
||||
username: string,
|
||||
): Promise<GitHubUserIssue | ServiceError> {
|
||||
return await this.executeQuery<GitHubUserIssue>(queryUserIssue, {
|
||||
username,
|
||||
});
|
||||
}
|
||||
async requestUserPullRequest(
|
||||
username: string,
|
||||
): Promise<GitHubUserPullRequest | null> {
|
||||
): Promise<GitHubUserPullRequest | ServiceError> {
|
||||
return await this.executeQuery<GitHubUserPullRequest>(
|
||||
queryUserPullRequest,
|
||||
{ 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
|
||||
const repository = await this.requestUserRepository(username);
|
||||
if (repository === null) return null;
|
||||
if (repository instanceof ServiceError) {
|
||||
Logger.error(repository);
|
||||
return repository;
|
||||
}
|
||||
|
||||
const promises = Promise.allSettled([
|
||||
this.requestUserActivity(username),
|
||||
|
|
@ -69,15 +77,34 @@ export class GithubApiService extends GithubRepository {
|
|||
];
|
||||
|
||||
if (status.includes("rejected")) {
|
||||
console.error(`Can not find a user with username:' ${username}'`);
|
||||
return null;
|
||||
Logger.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,
|
||||
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]}`,
|
||||
},
|
||||
});
|
||||
}) as QueryDefaultResponse<{ user: T; errors?: unknown[] }>;
|
||||
}) as QueryDefaultResponse<{ user: T }>;
|
||||
|
||||
if (response.data.data.errors) {
|
||||
throw new Error("Error from Github API", {
|
||||
cause: response.data.data.errors,
|
||||
});
|
||||
if (response?.data?.errors) {
|
||||
return this.handleError(response?.data?.errors);
|
||||
}
|
||||
|
||||
return response?.data?.data?.user ?? null;
|
||||
return response?.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));
|
||||
Logger.error(JSON.stringify(error.cause, null, 2));
|
||||
} else {
|
||||
console.error(error);
|
||||
Logger.error(error);
|
||||
}
|
||||
|
||||
return null;
|
||||
return new ServiceError("not found", EServiceKindError.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { Logger } from "../Helpers/Logger.ts";
|
||||
import { existsSync } from "./utils.ts";
|
||||
|
||||
export class CacheManager {
|
||||
|
|
@ -44,7 +45,7 @@ export class CacheManager {
|
|||
const data = new TextEncoder().encode(text);
|
||||
|
||||
Deno.writeFile(this.cacheFilePath, data, { create: true }).catch(() => {
|
||||
console.warn("Failed to save cache file");
|
||||
Logger.warn("Failed to save cache file");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,20 +1,24 @@
|
|||
import { CacheManager } from "./cache_manager.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
|
||||
const url = getUrl(request)
|
||||
const url = getUrl(request);
|
||||
|
||||
// if more conditions are added, make sure to create a variable to skipCache
|
||||
if (url.pathname === "/favicon.ico") {
|
||||
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);
|
||||
if (cacheManager.isCacheValid) {
|
||||
const cache = readCache(cacheManager.cacheFilePath)
|
||||
const cache = readCache(cacheManager.cacheFilePath);
|
||||
if (cache !== null) {
|
||||
return new Response(cache, {
|
||||
headers: options.headers ?? new Headers({}),
|
||||
|
|
@ -22,8 +26,11 @@ export async function staticRenderRegeneration(request: Request, options: Static
|
|||
}
|
||||
}
|
||||
|
||||
const response = await render(request)
|
||||
cacheManager.save(response)
|
||||
const response = await render(request);
|
||||
|
||||
return response
|
||||
if (response.status >= 200 && response.status < 300) {
|
||||
cacheManager.save(response);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
export interface StaticRegenerationOptions {
|
||||
// The number of milliseconds before the page should be revalidated
|
||||
revalidate?: number
|
||||
revalidate?: number;
|
||||
// The headers to be sent with the response
|
||||
headers?: Headers
|
||||
headers?: Headers;
|
||||
}
|
||||
|
|
@ -1,35 +1,36 @@
|
|||
export function getUrl(request: Request) {
|
||||
try {
|
||||
return new URL(request.url)
|
||||
return new URL(request.url);
|
||||
} catch {
|
||||
return {
|
||||
pathname: request.url,
|
||||
search: request.url
|
||||
}
|
||||
search: request.url,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function readCache(cacheFilePath: string): Uint8Array | null {
|
||||
try {
|
||||
return Deno.readFileSync(cacheFilePath)
|
||||
return Deno.readFileSync(cacheFilePath);
|
||||
} catch {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 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 data = encoder.encode(message);
|
||||
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
export const existsSync = (filename: string): boolean => {
|
||||
try {
|
||||
Deno.statSync(filename);
|
||||
|
|
@ -39,4 +40,3 @@ export const existsSync = (filename: string): boolean => {
|
|||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
4
src/Types/EServiceKindError.ts
Normal file
4
src/Types/EServiceKindError.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
export const enum EServiceKindError {
|
||||
RATE_LIMIT = "RATE_LIMITED",
|
||||
NOT_FOUND = "NOT_FOUND",
|
||||
}
|
||||
|
|
@ -1,5 +1,11 @@
|
|||
export type GithubError = {
|
||||
message: string;
|
||||
type: string;
|
||||
};
|
||||
|
||||
export type QueryDefaultResponse<T = unknown> = {
|
||||
data: {
|
||||
data: T;
|
||||
errors: GithubError[];
|
||||
};
|
||||
};
|
||||
|
|
|
|||
20
src/Types/ServiceError.ts
Normal file
20
src/Types/ServiceError.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1 +1,3 @@
|
|||
export * from './Request.ts'
|
||||
export * from "./Request.ts";
|
||||
export * from "./ServiceError.ts";
|
||||
export * from "./EServiceKindError.ts";
|
||||
|
|
|
|||
|
|
@ -14,6 +14,11 @@ export class Error400 extends BaseError {
|
|||
readonly message = "Bad Request";
|
||||
}
|
||||
|
||||
export class Error419 extends BaseError {
|
||||
readonly status = 419;
|
||||
readonly message = "Rate Limit Exceeded";
|
||||
}
|
||||
|
||||
export class Error404 extends BaseError {
|
||||
readonly status = 404;
|
||||
readonly message = "Not Found";
|
||||
|
|
|
|||
23
src/pages/Error.ts
Normal file
23
src/pages/Error.ts
Normal 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;
|
||||
}
|
||||
|
|
@ -550,7 +550,7 @@ export const COLORS: {[name: string]: Theme} = {
|
|||
DEFAULT_RANK_BASE: "#7f6ceb",
|
||||
DEFAULT_RANK_SHADOW: "#a598ed",
|
||||
DEFAULT_RANK_TEXT: "#7f6ceb",
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export interface Theme {
|
||||
|
|
@ -577,4 +577,3 @@ export interface Theme {
|
|||
DEFAULT_RANK_SHADOW: string;
|
||||
DEFAULT_RANK_TEXT: string;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { getTrophyIcon, getNextRankBar } from "./icons.ts";
|
||||
import { CONSTANTS, RANK, abridgeScore, RANK_ORDER } from "./utils.ts";
|
||||
import { getNextRankBar, getTrophyIcon } from "./icons.ts";
|
||||
import { abridgeScore, CONSTANTS, RANK, RANK_ORDER } from "./utils.ts";
|
||||
import { Theme } from "./theme.ts";
|
||||
|
||||
class RankCondition {
|
||||
|
|
@ -10,7 +10,6 @@ class RankCondition {
|
|||
) {}
|
||||
}
|
||||
|
||||
|
||||
export class Trophy {
|
||||
rankCondition: RankCondition | null = null;
|
||||
rank: RANK = RANK.UNKNOWN;
|
||||
|
|
@ -59,14 +58,16 @@ export class Trophy {
|
|||
const result = progress / distance;
|
||||
return result;
|
||||
}
|
||||
render(theme: Theme,
|
||||
render(
|
||||
theme: Theme,
|
||||
x = 0,
|
||||
y = 0,
|
||||
panelSize = CONSTANTS.DEFAULT_PANEL_SIZE,
|
||||
noBackground = CONSTANTS.DEFAULT_NO_BACKGROUND,
|
||||
noFrame = CONSTANTS.DEFAULT_NO_FRAME,
|
||||
): string {
|
||||
const { BACKGROUND: PRIMARY, TITLE: SECONDARY, TEXT, NEXT_RANK_BAR } = theme;
|
||||
const { BACKGROUND: PRIMARY, TITLE: SECONDARY, TEXT, NEXT_RANK_BAR } =
|
||||
theme;
|
||||
const nextRankBar = getNextRankBar(
|
||||
this.title,
|
||||
this.calculateNextRankPercentage(),
|
||||
|
|
@ -90,8 +91,8 @@ export class Trophy {
|
|||
height="${panelSize - 1}"
|
||||
stroke="#e1e4e8"
|
||||
fill="${PRIMARY}"
|
||||
stroke-opacity="${noFrame ? '0' : '1'}"
|
||||
fill-opacity="${noBackground ? '0' : '1'}"
|
||||
stroke-opacity="${noFrame ? "0" : "1"}"
|
||||
fill-opacity="${noBackground ? "0" : "1"}"
|
||||
/>
|
||||
${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>
|
||||
|
|
@ -131,7 +132,7 @@ export class AllSuperRankTrophy extends Trophy{
|
|||
super(score, rankConditions);
|
||||
this.title = "AllSuperRank";
|
||||
this.filterTitles = ["AllSuperRank"];
|
||||
this.bottomMessage = "All S Rank"
|
||||
this.bottomMessage = "All S Rank";
|
||||
this.hidden = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -147,7 +148,7 @@ export class Joined2020Trophy extends Trophy{
|
|||
super(score, rankConditions);
|
||||
this.title = "Joined2020";
|
||||
this.filterTitles = ["Joined2020"];
|
||||
this.bottomMessage = "Joined 2020"
|
||||
this.bottomMessage = "Joined 2020";
|
||||
this.hidden = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -163,7 +164,7 @@ export class AncientAccountTrophy extends Trophy{
|
|||
super(score, rankConditions);
|
||||
this.title = "AncientUser";
|
||||
this.filterTitles = ["AncientUser"];
|
||||
this.bottomMessage = "Before 2010"
|
||||
this.bottomMessage = "Before 2010";
|
||||
this.hidden = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -211,7 +212,7 @@ export class OGAccountTrophy extends Trophy{
|
|||
super(score, rankConditions);
|
||||
this.title = "OGUser";
|
||||
this.filterTitles = ["OGUser"];
|
||||
this.bottomMessage = "Joined 2008"
|
||||
this.bottomMessage = "Joined 2008";
|
||||
this.hidden = true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,22 +1,22 @@
|
|||
import {
|
||||
Trophy,
|
||||
TotalStarTrophy,
|
||||
AllSuperRankTrophy,
|
||||
AncientAccountTrophy,
|
||||
Joined2020Trophy,
|
||||
LongTimeAccountTrophy,
|
||||
MultipleLangTrophy,
|
||||
MultipleOrganizationsTrophy,
|
||||
OGAccountTrophy,
|
||||
TotalCommitTrophy,
|
||||
TotalFollowerTrophy,
|
||||
TotalIssueTrophy,
|
||||
TotalPullRequestTrophy,
|
||||
TotalRepositoryTrophy,
|
||||
TotalReviewsTrophy,
|
||||
MultipleLangTrophy,
|
||||
LongTimeAccountTrophy,
|
||||
AncientAccountTrophy,
|
||||
OGAccountTrophy,
|
||||
Joined2020Trophy,
|
||||
AllSuperRankTrophy,
|
||||
MultipleOrganizationsTrophy,
|
||||
TotalStarTrophy,
|
||||
Trophy,
|
||||
} from "./trophy.ts";
|
||||
import { UserInfo } from "./user_info.ts";
|
||||
import { RANK_ORDER, RANK } from "./utils.ts";
|
||||
import { RANK, RANK_ORDER } from "./utils.ts";
|
||||
|
||||
export class TrophyList {
|
||||
private trophies = new Array<Trophy>();
|
||||
|
|
@ -49,7 +49,9 @@ export class TrophyList {
|
|||
return this.trophies;
|
||||
}
|
||||
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() {
|
||||
this.trophies = this.trophies.filter((trophy) =>
|
||||
|
|
@ -64,9 +66,9 @@ export class TrophyList {
|
|||
filterByRanks(ranks: Array<string>) {
|
||||
if (ranks.filter((rank) => rank.includes("-")).length !== 0) {
|
||||
this.trophies = this.trophies.filter((trophy) =>
|
||||
!ranks.map(rank => rank.substring(1)).includes(trophy.rank)
|
||||
)
|
||||
return
|
||||
!ranks.map((rank) => rank.substring(1)).includes(trophy.rank)
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.trophies = this.trophies.filter((trophy) =>
|
||||
ranks.includes(trophy.rank)
|
||||
|
|
@ -78,4 +80,3 @@ export class TrophyList {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -88,15 +88,18 @@ export class UserInfo {
|
|||
const joined2020 = new Date(userActivity.createdAt).getFullYear() == 2020
|
||||
? 1
|
||||
: 0;
|
||||
const ogAccount =
|
||||
new Date(userActivity.createdAt).getFullYear() <= 2008 ? 1 : 0;
|
||||
const ogAccount = new Date(userActivity.createdAt).getFullYear() <= 2008
|
||||
? 1
|
||||
: 0;
|
||||
|
||||
this.totalCommits = totalCommits;
|
||||
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.totalPullRequests = userPullRequest.pullRequests.totalCount;
|
||||
this.totalReviews = userActivity.contributionsCollection.totalPullRequestReviewContributions;
|
||||
this.totalReviews =
|
||||
userActivity.contributionsCollection.totalPullRequestReviewContributions;
|
||||
this.totalStargazers = totalStargazers;
|
||||
this.totalRepositories = userRepository.repositories.totalCount;
|
||||
this.languageCount = languages.size;
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue