Skip to content

Commit

Permalink
feat: 改用 got,移除 axios
Browse files Browse the repository at this point in the history
  • Loading branch information
SALTWOOD committed Sep 7, 2024
1 parent 3c5cf21 commit 28b1f72
Show file tree
Hide file tree
Showing 8 changed files with 33 additions and 102 deletions.
78 changes: 0 additions & 78 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
"@types/express": "^4.17.21",
"@types/node": "^22.5.0",
"avsc": "^5.7.7",
"axios": "^1.7.5",
"better-sqlite3": "^11.2.1",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
Expand Down
3 changes: 2 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import dotenv from 'dotenv'
import env from 'env-var'
import { Utilities } from './utilities'
import { Utilities } from './utilities.js'

export class Config {
public static instance: Config
Expand All @@ -14,6 +14,7 @@ export class Config {
public readonly certificateDir: string = env.get('CERTIFICATE_DIRECTORY').default("./certificates").asString()
public readonly port: number = env.get('PORT').default(9388).asPortNumber()
public readonly adminToken: string = env.get('ADMIN_TOKEN').default(Utilities.generateRandomString(24)).asString()
public static readonly version: string = "3.0.2";

private constructor() { }

Expand Down
4 changes: 2 additions & 2 deletions src/database/github-user.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Table } from "../sqlite";
import { UserEntity } from "./user";
import { Table } from "../sqlite.js";
import { UserEntity } from "./user.js";

@Table('github_users', `
id INTEGER PRIMARY KEY,
Expand Down
6 changes: 3 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { exec } from "child_process";
import { Config } from "./config";
import { Server } from "./server";
import { Utilities } from "./utilities";
import { Config } from "./config.js";
import { Server } from "./server.js";
import { Utilities } from "./utilities.js";

function onStop(signal: string) {
server.db.close();
Expand Down
31 changes: 18 additions & 13 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import path from 'path';
import { Server as SocketIOServer } from 'socket.io';
// import cors from 'cors';
import JwtHelper from './jwt-helper.js';
import axios from 'axios';
import { SQLiteHelper } from './sqlite.js';
import { UserEntity } from './database/user.js';
import { ClusterEntity } from './database/cluster.js';
Expand All @@ -19,7 +18,7 @@ import { HourlyStatsStorage } from './statistics/hourly-stats.js';
import cookieParser from 'cookie-parser';
import { Plugin } from './plugin/Plugin.js';
import { PluginLoader } from './plugin/PluginLoader.js';
import { Got } from 'got';
import got, {type Got} from 'got'

// 创建一个中间件函数
const logMiddleware = (req: Request, res: Response, next: NextFunction) => {
Expand Down Expand Up @@ -52,6 +51,7 @@ export class Server {
protected centerStats: HourlyStatsStorage;
protected plugins: Plugin[];
protected pluginLoader: PluginLoader;
protected got: Got;

public constructor() {
this.plugins = [];
Expand All @@ -63,6 +63,12 @@ export class Server {
})
.catch(error => console.error(error));

this.got = got.extend({
headers: {
'User-Agent': `93AtHome-V3/${Config.version}`
}
});

this.files = [];
this.avroBytes = new Uint8Array();

Expand Down Expand Up @@ -192,28 +198,27 @@ export class Server {
const code = req.query.code as string || '';

// 请求GitHub获取access_token
const tokenResponse = await axios.post(`https://${Config.getInstance().githubUrl}/login/oauth/access_token`, {
code,
client_id: Config.getInstance().githubOAuthClientId,
client_secret: Config.getInstance().githubOAuthClientSecret
}, {
headers: {
'Accept': 'application/json'
}
const tokenResponse = await this.got.post(`https://${Config.getInstance().githubUrl}/login/oauth/access_token`, {
json: {
code,
client_id: Config.getInstance().githubOAuthClientId,
client_secret: Config.getInstance().githubOAuthClientSecret
},
responseType: 'json'
});

const tokenData = tokenResponse.data as { access_token: string };
const tokenData = tokenResponse.body as { access_token: string };
const accessToken = tokenData.access_token;

let userResponse;
try {
userResponse = await axios.get(`https://${Config.getInstance().githubApiUrl}/user`, {
userResponse = await this.got.get(`https://${Config.getInstance().githubApiUrl}/user`, {
headers: {
'Authorization': `token ${accessToken}`,
'Accept': 'application/json',
'User-Agent': 'Open93AtHome-V3/3.0.0' // GitHub API要求设置User-Agent
}
}).then(response => response.data) as { id: number, login: string, avatar_url: string, name: string };
}).then(response => response.body) as { id: number, login: string, avatar_url: string, name: string };
} catch (error) {
console.error('Error fetching GitHub user info: ', error as Error);
throw error; // 或者返回一个默认的错误响应
Expand Down
2 changes: 1 addition & 1 deletion src/sqlite.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Database from 'better-sqlite3';
import { ClusterEntity } from './database/cluster';
import { ClusterEntity } from './database/cluster.js';

// 表的定义映射
const tableSchemaMap = new Map<Function, string>();
Expand Down
10 changes: 7 additions & 3 deletions src/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import JwtHelper from './jwt-helper.js';
import { File, IFileInfo } from './database/file.js';
import { compress } from '@mongodb-js/zstd';
import avsc from 'avsc';
import axios from 'axios';
import { exec } from 'child_process';
import { ClusterEntity } from './database/cluster.js';
import { SQLiteHelper } from './sqlite.js';
import { UserEntity } from './database/user.js';
import got, { Got } from 'got';

export const FileListSchema = avsc.Type.forSchema({
type: 'array',
Expand All @@ -27,6 +27,8 @@ export const FileListSchema = avsc.Type.forSchema({
})

export class Utilities {
public static got: Got = got.extend();

public static isRunningInDocker(): boolean {
return process.env.IS_IN_DOCKER === 'true';
}
Expand Down Expand Up @@ -156,8 +158,10 @@ export class Utilities {

public static async checkUrl(url: string): Promise<{ url: string; hash: string }> {
try {
const response = await axios.get(url, { responseType: 'arraybuffer' });
const responseData = response.data as Buffer;
const response = await got.get(url, {
responseType: 'buffer'
});
const responseData = response.body as Buffer;

// 计算响应数据的哈希值
const hash = crypto.createHash('sha1').update(responseData).digest('hex');
Expand Down

0 comments on commit 28b1f72

Please sign in to comment.