Skip to content

Commit

Permalink
refactor: use egg v4
Browse files Browse the repository at this point in the history
BREAKING CHANGE: only support egg >= 4.0.0

the first app on egg v4
eggjs/egg#3644
  • Loading branch information
fengmk2 committed Feb 4, 2025
1 parent 4012f58 commit 7aa829c
Show file tree
Hide file tree
Showing 149 changed files with 203 additions and 198 deletions.
8 changes: 4 additions & 4 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"extends": "eslint-config-egg/typescript",
"rules": {

}
"extends": [
"eslint-config-egg/typescript",
"eslint-config-egg/lib/rules/enforce-node-prefix"
]
}
4 changes: 2 additions & 2 deletions INTEGRATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
{
redis: {
enable: true,
package: 'egg-redis',
package: '@eggjs/redis',
},
teggOrm: {
enable: true,
Expand All @@ -71,7 +71,7 @@
},
tracer: {
enable: true,
package: 'egg-tracer',
package: '@eggjs/tracer',
},
typeboxValidate: {
enable: true,
Expand Down
4 changes: 2 additions & 2 deletions app.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import path from 'path';
import { readFile } from 'fs/promises';
import path from 'node:path';
import { readFile } from 'node:fs/promises';
import { Application } from 'egg';
import { ChangesStreamService } from './app/core/service/ChangesStreamService';

Expand Down
2 changes: 1 addition & 1 deletion app/common/CryptoUtil.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { generateKeyPairSync } from 'crypto';
import { generateKeyPairSync } from 'node:crypto';
import NodeRSA from 'node-rsa';

// generate rsa key pair
Expand Down
2 changes: 1 addition & 1 deletion app/common/UserUtil.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import crypto from 'crypto';
import crypto from 'node:crypto';
import base from 'base-x';
import { crc32 } from '@node-rs/crc32';
import * as ssri from 'ssri';
Expand Down
4 changes: 2 additions & 2 deletions app/common/adapter/CacheAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import {
AccessLevel,
Inject,
} from '@eggjs/tegg';
// FIXME: egg-redis should use ioredis v5
// https://github.com/eggjs/egg-redis/issues/35
// FIXME: @eggjs/redis should use ioredis v5
// https://github.com/eggjs/redis/issues/35
import type { Redis } from 'ioredis';

const ONE_DAY = 3600 * 24;
Expand Down
4 changes: 2 additions & 2 deletions app/common/adapter/NFSAdapter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Readable } from 'stream';
import { Readable } from 'node:stream';
import { IncomingHttpHeaders } from 'node:http';
import {
SingletonProto,
AccessLevel,
Expand All @@ -8,7 +9,6 @@ import { Pointcut } from '@eggjs/tegg/aop';
import { EggLogger } from 'egg';
import { AsyncTimer } from '../aop/AsyncTimer';
import { NFSClient } from '../typing';
import { IncomingHttpHeaders } from 'http';

const INSTANCE_NAME = 'nfsAdapter';

Expand Down
2 changes: 1 addition & 1 deletion app/common/adapter/NPMRegistry.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { setTimeout } from 'timers/promises';
import { setTimeout } from 'node:timers/promises';
import {
ContextProto,
AccessLevel,
Expand Down
2 changes: 1 addition & 1 deletion app/common/adapter/binary/BucketBinary.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SingletonProto } from '@eggjs/tegg';
import { BinaryType } from '../../enum/Binary';
import binaries, { BinaryName, BinaryTaskConfig } from '../../../../config/binaries';
import path from 'path';
import path from 'node:path';
import { AbstractBinary, FetchResult, BinaryItem, BinaryAdapter } from './AbstractBinary';

@SingletonProto()
Expand Down
2 changes: 1 addition & 1 deletion app/common/adapter/binary/ChromeForTestingBinary.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { basename } from 'path';
import { basename } from 'node:path';
import { SingletonProto } from '@eggjs/tegg';
import { BinaryType } from '../../enum/Binary';
import { AbstractBinary, FetchResult, BinaryItem, BinaryAdapter } from './AbstractBinary';
Expand Down
2 changes: 1 addition & 1 deletion app/common/adapter/binary/NodePreGypBinary.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SingletonProto } from '@eggjs/tegg';
import { BinaryType } from '../../enum/Binary';
import binaries, { BinaryName } from '../../../../config/binaries';
import { join } from 'path';
import { join } from 'node:path';
import { AbstractBinary, FetchResult, BinaryItem, BinaryAdapter } from './AbstractBinary';

@SingletonProto()
Expand Down
4 changes: 2 additions & 2 deletions app/common/adapter/binary/PlaywrightBinary.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

import { AbstractBinary, BinaryAdapter, BinaryItem, FetchResult } from './AbstractBinary';
import util from 'util';
import path from 'path';
import util from 'node:util';
import path from 'node:path';
import { SingletonProto } from '@eggjs/tegg';
import { BinaryType } from '../../enum/Binary';

Expand Down
2 changes: 1 addition & 1 deletion app/common/aop/AsyncTimer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { performance } from 'perf_hooks';
import { performance } from 'node:perf_hooks';
import { Advice, AdviceContext, IAdvice } from '@eggjs/tegg/aop';
import { Inject } from '@eggjs/tegg';
import { EggLogger } from 'egg';
Expand Down
6 changes: 3 additions & 3 deletions app/common/typing.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { CnpmcoreConfig } from '../port/config';
import { Readable } from 'stream';
import { IncomingHttpHeaders } from 'http';
import { Readable } from 'node:stream';
import { IncomingHttpHeaders } from 'node:http';
import { EggContext } from '@eggjs/tegg';
import { estypes } from '@elastic/elasticsearch';
import { CnpmcoreConfig } from '../port/config';

export interface UploadResult {
key: string;
Expand Down
2 changes: 1 addition & 1 deletion app/core/entity/Hook.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Entity, EntityData } from './Entity';
import { EasyData, EntityUtil } from '../util/EntityUtil';
import { HookType } from '../../common/enum/Hook';
import crypto from 'crypto';
import crypto from 'node:crypto';

export type CreateHookData = Omit<EasyData<HookData, 'hookId'>, 'enable' | 'latestTaskId'>;

Expand Down
4 changes: 2 additions & 2 deletions app/core/entity/Task.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os from 'os';
import path from 'path';
import os from 'node:os';
import path from 'node:path';
import { Entity, EntityData } from './Entity';
import { EasyData, EntityUtil } from '../util/EntityUtil';
import { TaskType, TaskState } from '../../common/enum/Task';
Expand Down
5 changes: 2 additions & 3 deletions app/core/service/BinarySyncerService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { rm } from 'fs/promises';
import {
AccessLevel,
SingletonProto,
Expand All @@ -8,7 +7,7 @@ import {
import {
EggHttpClient,
} from 'egg';
import fs from 'fs/promises';
import fs from 'node:fs/promises';
import { sortBy } from 'lodash';
import binaries, { BinaryName, CategoryName } from '../../../config/binaries';
import { BinaryRepository } from '../../repository/BinaryRepository';
Expand Down Expand Up @@ -223,7 +222,7 @@ export class BinarySyncerService extends AbstractService {
logs = [];
} finally {
if (localFile) {
await rm(localFile, { force: true });
await fs.rm(localFile, { force: true });
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions app/core/service/ChangesStreamService.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os from 'os';
import { setTimeout } from 'timers/promises';
import os from 'node:os';
import { setTimeout } from 'node:timers/promises';
import {
AccessLevel,
SingletonProto,
Expand Down
8 changes: 4 additions & 4 deletions app/core/service/ProxyCacheService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { EggHttpClient, HttpClientRequestOptions, HttpClientResponse } from 'egg';
import { EggHttpClient, HttpClientRequestOptions, HttpClientResponse, Context } from 'egg';
import { ForbiddenError } from 'egg-errors';
import { SingletonProto, AccessLevel, Inject, EggContext } from '@eggjs/tegg';
import { SingletonProto, AccessLevel, Inject } from '@eggjs/tegg';
import { BackgroundTaskHelper } from '@eggjs/tegg-background-task';
import { valid as semverValid } from 'semver';
import { AbstractService } from '../../common/AbstractService';
Expand Down Expand Up @@ -51,7 +51,7 @@ export class ProxyCacheService extends AbstractService {
@Inject()
private readonly backgroundTaskHelper:BackgroundTaskHelper;

async getPackageVersionTarResponse(fullname: string, ctx: EggContext): Promise<HttpClientResponse> {
async getPackageVersionTarResponse(fullname: string, ctx: Context): Promise<HttpClientResponse> {
if (this.config.cnpmcore.syncPackageBlockList.includes(fullname)) {
throw new ForbiddenError(`stop proxy by block list: ${JSON.stringify(this.config.cnpmcore.syncPackageBlockList)}`);
}
Expand Down Expand Up @@ -244,7 +244,7 @@ export class ProxyCacheService extends AbstractService {
await this.nfsAdapter.uploadBytes(storeKey, nfsBytes);
}

async getProxyResponse(ctx: Partial<EggContext>, options?: HttpClientRequestOptions): Promise<HttpClientResponse> {
async getProxyResponse(ctx: Partial<Context>, options?: HttpClientRequestOptions): Promise<HttpClientResponse> {
const registry = this.npmRegistry.registry;
const remoteAuthToken = await this.registryManagerService.getAuthTokenByRegistryHost(registry);
const authorization = this.npmRegistry.genAuthorizationHeader(remoteAuthToken);
Expand Down
2 changes: 1 addition & 1 deletion app/core/service/UserService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import crypto from 'crypto';
import crypto from 'node:crypto';
import {
AccessLevel,
SingletonProto,
Expand Down
2 changes: 1 addition & 1 deletion app/infra/AuthAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
SingletonProto,
} from '@eggjs/tegg';
import { Redis } from 'ioredis';
import { randomUUID } from 'crypto';
import { randomUUID } from 'node:crypto';
import { AuthClient, AuthUrlResult, userResult } from '../common/typing';

const ONE_DAY = 3600 * 24;
Expand Down
2 changes: 1 addition & 1 deletion app/infra/NFSClientAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
import { EggAppConfig, EggLogger } from 'egg';
import FSClient from 'fs-cnpm';
import { AppendResult, NFSClient, UploadOptions, UploadResult, DownloadOptions } from '../common/typing';
import { Readable } from 'stream';
import { Readable } from 'node:stream';

@SingletonProto({
name: 'nfsClient',
Expand Down
8 changes: 7 additions & 1 deletion app/port/UserRoleManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export class UserRoleManager {
};
}
this.handleAuthorized = true;
const authorization = ctx.get('authorization');
const authorization = ctx.get<string>('authorization');
if (!authorization) return null;
const authorizedUserAndToken = await this.tokenService.getUserAndToken(authorization);
if (!authorizedUserAndToken) {
Expand Down Expand Up @@ -187,3 +187,9 @@ export class UserRoleManager {
return user.name in this.config.cnpmcore.admins;
}
}

declare module 'egg' {
export interface Context {
userId?: string;
}
}
2 changes: 1 addition & 1 deletion app/port/controller/BinarySyncController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
EggContext,
Inject,
} from '@eggjs/tegg';
import path from 'path';
import path from 'node:path';
import { NotFoundError } from 'egg-errors';
import { AbstractController } from './AbstractController';
import { BinarySyncerService } from '../../core/service/BinarySyncerService';
Expand Down
2 changes: 1 addition & 1 deletion app/port/controller/HomeController.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { performance } from 'perf_hooks';
import { performance } from 'node:perf_hooks';
import {
HTTPController,
HTTPMethod,
Expand Down
2 changes: 1 addition & 1 deletion app/port/controller/package/DownloadPackageVersionTar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export class DownloadPackageVersionTarController extends AbstractController {
private async getTgzProxyStream(ctx: EggContext, fullname: string, version: string) {
const { headers, status, res } = await this.proxyCacheService.getPackageVersionTarResponse(fullname, ctx);
ctx.status = status;
ctx.set(headers as { [key: string]: string | string[] });
ctx.set(headers as Record<string, string>);
ctx.runInBackground(async () => {
const task = await this.packageSyncerService.createTask(fullname, {
authorIp: ctx.ip,
Expand Down
4 changes: 2 additions & 2 deletions app/port/controller/package/SavePackageVersionController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,9 +268,9 @@ export class SavePackageVersionController extends AbstractController {
// forbidden star/unstar request
// npm@6: referer: 'star [REDACTED]'
// npm@>=7: 'npm-command': 'star'
let command = ctx.get('npm-command');
let command = ctx.get<string>('npm-command');
if (!command) {
command = ctx.get('referer').split(' ', 1)[0];
command = ctx.get<string>('referer').split(' ', 1)[0];
}
if (command === 'star' || command === 'unstar') {
throw new ForbiddenError(`npm ${command} is not allowed`);
Expand Down
2 changes: 1 addition & 1 deletion app/port/controller/package/ShowPackageController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class ShowPackageController extends AbstractController {
try {
const cacheEtag = await this.cacheService.getPackageEtag(fullname, isFullManifests);
if (!isSync && cacheEtag) {
let requestEtag = ctx.request.get('if-none-match');
let requestEtag = ctx.request.get<string>('if-none-match');
if (requestEtag.startsWith('W/')) {
requestEtag = requestEtag.substring(2);
}
Expand Down
4 changes: 2 additions & 2 deletions app/port/controller/package/UpdatePackageController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ export class UpdatePackageController extends AbstractController {
private getNpmCommand(ctx: EggContext) {
// npm@6: referer: 'xxx [REDACTED]'
// npm@>=7: 'npm-command': 'xxx'
let npmCommand = ctx.get('npm-command');
let npmCommand = ctx.get<string>('npm-command');
if (!npmCommand) {
npmCommand = ctx.get('referer').split(' ', 1)[0];
npmCommand = ctx.get<string>('referer').split(' ', 1)[0];
}

return npmCommand;
Expand Down
8 changes: 4 additions & 4 deletions app/port/middleware/ErrorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ export async function ErrorHandler(ctx: EggContext, next: Next) {
if (err.name === 'PackageNotFoundError') {
if (err.syncPackage) {
// create sync task
const syncPacakge = err.syncPackage;
const syncPackage = err.syncPackage;
const packageSyncerService = await ctx.getEggObject(PackageSyncerService);
const task = await packageSyncerService.createTask(syncPacakge.fullname, {
const task = await packageSyncerService.createTask(syncPackage.fullname, {
authorIp: ctx.ip,
authorId: ctx.userId,
tips: `Sync cause by "${syncPacakge.fullname}" missing, request URL "${ctx.href}"`,
tips: `Sync cause by "${syncPackage.fullname}" missing, request URL "${ctx.href}"`,
});
ctx.logger.info('[middleware:ErrorHandler][syncPackage] create sync package "%s" task %s',
syncPacakge.fullname, task.taskId);
syncPackage.fullname, task.taskId);
}
if (err.redirectToSourceRegistry) {
// redirect to sourceRegistry
Expand Down
4 changes: 2 additions & 2 deletions app/port/schedule/CleanTempDir.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { EggAppConfig, EggLogger } from 'egg';
import { CronParams, Schedule, ScheduleType } from '@eggjs/tegg/schedule';
import { Inject } from '@eggjs/tegg';
import { rm, access } from 'fs/promises';
import path from 'path';
import { rm, access } from 'node:fs/promises';
import path from 'node:path';
import dayjs from '../../common/dayjs';

@Schedule<CronParams>({
Expand Down
2 changes: 1 addition & 1 deletion app/port/webauth/WebauthController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
} from 'egg';
import { Static, Type } from '@sinclair/typebox';
import { ForbiddenError, NotFoundError } from 'egg-errors';
import { createHash } from 'crypto';
import { createHash } from 'node:crypto';
import base64url from 'base64url';
import {
generateRegistrationOptions,
Expand Down
2 changes: 1 addition & 1 deletion config/config.unittest.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { join } from 'path';
import { join } from 'node:path';
import { EggAppConfig, PowerPartial } from 'egg';
import Mock from '@elastic/elasticsearch-mock';
import { database } from './database';
Expand Down
4 changes: 2 additions & 2 deletions config/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,15 @@ const plugin: EggPlugin = {
},
tracer: {
enable: true,
package: 'egg-tracer',
package: '@eggjs/tracer',
},
typeboxValidate: {
enable: true,
package: 'egg-typebox-validate',
},
redis: {
enable: true,
package: 'egg-redis',
package: '@eggjs/redis',
},
cors: {
enable: true,
Expand Down
2 changes: 1 addition & 1 deletion module.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ declare module "egg" {
export interface EggContextModule {
cnpmcoreCore: ContextCnpmcore;
}
};
}
Loading

0 comments on commit 7aa829c

Please sign in to comment.