Skip to content

Commit

Permalink
feat: hello cnpmcore
Browse files Browse the repository at this point in the history
  • Loading branch information
elrrrrrrr committed Feb 24, 2023
1 parent 4527319 commit bed580f
Show file tree
Hide file tree
Showing 10 changed files with 280 additions and 5 deletions.
11 changes: 8 additions & 3 deletions hello-tegg/app/controller/HelloController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import {
Middleware,
Inject,
} from '@eggjs/tegg';
import { EggLogger } from 'egg';
import { traceMethod } from 'app/middleware/trace_method';
import { HelloService } from 'app/biz/HelloService';
import { EggHttpClient, EggLogger } from 'egg';
import { traceMethod } from '../middleware/trace_method';
import { HelloService } from '../biz/HelloService';

@HTTPController()
@Middleware(traceMethod)
Expand All @@ -21,13 +21,18 @@ export class HelloController {
@Inject()
private readonly logger: EggLogger;

@Inject()
private readonly httpclient: EggHttpClient;

@HTTPMethod({
method: HTTPMethodEnum.GET,
path: '/hello',
})
async hello(@Context() ctx: EggContext, @HTTPQuery() name: string) {
this.logger.info('access url: %s', ctx.url);

await this.httpclient.request(`${ctx.origin}/-/v1/login/sso/${name}`, { method: 'POST' });

const message = await this.helloService.hello(name);

return {
Expand Down
29 changes: 29 additions & 0 deletions hello-tegg/app/infra/AuthAdapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { AccessLevel, EggContext, SingletonProto } from '@eggjs/tegg';
import { AuthAdapter } from 'cnpmcore/infra/AuthAdapter';
import { randomUUID } from 'crypto';
import { AuthUrlResult, userResult } from 'node_modules/cnpmcore/dist/app/common/typing';

const ONE_DAY = 3600 * 24;

@SingletonProto({
name: 'authAdapter',
accessLevel: AccessLevel.PUBLIC,
})
export class MyAuthAdapter extends AuthAdapter {
async getAuthUrl(ctx: EggContext): Promise<AuthUrlResult> {
const sessionId = randomUUID();
await this.redis.setex(sessionId, ONE_DAY, '');
return {
// 替换实际企业内的登录中心地址
loginUrl: `${ctx.origin}/hello?name=${sessionId}`,
doneUrl: `${ctx.href}/done/session/${sessionId}`,
};
}

async ensureCurrentUser(): Promise<userResult | null> {
return {
name: 'hello',
email: 'hello@cnpmjs.org',
};
}
}
9 changes: 9 additions & 0 deletions hello-tegg/app/infra/NFSAdapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { AccessLevel, SingletonProto } from '@eggjs/tegg';
import { NFSClientAdapter } from 'cnpmcore/infra/NFSClientAdapter';

@SingletonProto({
name: 'nfsClient',
accessLevel: AccessLevel.PUBLIC,
})
export class MyNFSClient extends NFSClientAdapter{
}
9 changes: 9 additions & 0 deletions hello-tegg/app/infra/QueueAdapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { AccessLevel, SingletonProto } from '@eggjs/tegg';
import { RedisQueueAdapter } from 'cnpmcore/infra/QueueAdapter';

@SingletonProto({
name: 'queueAdapter',
accessLevel: AccessLevel.PUBLIC,
})
export class MyQueueAdapter extends RedisQueueAdapter {
}
6 changes: 6 additions & 0 deletions hello-tegg/app/infra/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "infra",
"eggModule": {
"name": "infra"
}
}
172 changes: 172 additions & 0 deletions hello-tegg/config/config.default.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,182 @@
import assert from 'assert';
import { join } from 'path';
import { EggAppConfig, PowerPartial } from 'egg';
import OSSClient from 'oss-cnpm';
import { patchAjv } from 'cnpmcore/port/typebox';
import { SyncDeleteMode, SyncMode } from 'cnpmcore/common/constants';

export default (appInfo: EggAppConfig) => {
const config = {} as PowerPartial<EggAppConfig>;

// override config from framework / plugin
config.keys = appInfo.name + '123456';

config.cnpmcore = {
name: 'cnpm',
hooksLimit: 20,
sourceRegistry: 'https://registry.npmjs.org',
// upstream registry is base on `cnpmcore` or not
// if your upstream is official npm registry, please turn it off
sourceRegistryIsCNpm: false,
syncUpstreamFirst: false,
// 3 mins
sourceRegistrySyncTimeout: 180000,
taskQueueHighWaterSize: 100,
// sync mode
// - none: don't sync npm package, just redirect it to sourceRegistry
// - all: sync all npm packages
// - exist: only sync exist packages, effected when `enableCheckRecentlyUpdated` or `enableChangesStream` is enabled
syncMode: SyncMode.none,
syncDeleteMode: SyncDeleteMode.delete,
hookEnable: false,
syncPackageWorkerMaxConcurrentTasks: 10,
triggerHookWorkerMaxConcurrentTasks: 10,
createTriggerHookWorkerMaxConcurrentTasks: 10,
// stop syncing these packages in future
syncPackageBlockList: [],
// check recently from https://www.npmjs.com/browse/updated, if use set changesStreamRegistry to cnpmcore,
// maybe you should disable it
enableCheckRecentlyUpdated: true,
// mirror binary, default is false
enableSyncBinary: false,
// cnpmcore api: https://r.cnpmjs.org/-/binary
syncBinaryFromAPISource: '',
// enable sync downloads data from source registry https://github.com/cnpm/cnpmcore/issues/108
// all three parameters must be configured at the same time to take effect
enableSyncDownloadData: false,
syncDownloadDataSourceRegistry: '',
syncDownloadDataMaxDate: '', // should be YYYY-MM-DD format
// https://github.com/npm/registry-follower-tutorial
enableChangesStream: false,
checkChangesStreamInterval: 500,
changesStreamRegistry: 'https://replicate.npmjs.com',
// handle _changes request mode, default is 'streaming', please set it to 'json' when on cnpmcore registry
changesStreamRegistryMode: 'streaming',
registry: 'http://localhost:7001',
// https://docs.npmjs.com/cli/v6/using-npm/config#always-auth npm <= 6
// if `alwaysAuth=true`, all api request required access token
alwaysAuth: false,
// white scope list
allowScopes: [
'@cnpm',
'@cnpmcore',
'@example',
],
// allow publish non-scope package, disable by default
allowPublishNonScopePackage: false,
// Public registration is allowed, otherwise only admins can login
allowPublicRegistration: true,
// default system admins
admins: {
// name: email
cnpmcore_admin: 'admin@cnpmjs.org',
},
// http response cache control header
enableCDN: false,
// if you are using CDN, can set it to 'max-age=0, s-maxage=120, must-revalidate'
// it meaning cache 10s on CDN server and no cache on client side.
cdnCacheControlHeader: 'max-age=0, s-maxage=120, must-revalidate',
// if you are using CDN, can set it to 'Accept, Accept-Encoding'
cdnVaryHeader: 'Accept, Accept-Encoding',
// store full package version manifests data to database table(package_version_manifests), default is false
enableStoreFullPackageVersionManifestsToDatabase: false,
// only support npm as client and npm >= 7.0.0 allow publish action
enableNpmClientAndVersionCheck: true,
// sync when package not found, only effect when syncMode = all/exist
syncNotFound: false,
// redirect to source registry when package not found, only effect when syncMode = all/exist
redirectNotFound: true,
};

// override config from framework / plugin
config.dataDir = join(appInfo.root, '.cnpmcore');

config.orm = {
client: 'mysql',
database: process.env.MYSQL_DATABASE || 'cnpmcore',
host: process.env.MYSQL_HOST || '127.0.0.1',
port: process.env.MYSQL_PORT || 3306,
user: process.env.MYSQL_USER || 'root',
password: process.env.MYSQL_PASSWORD,
charset: 'utf8mb4',
};
if (process.env.DEBUG_LOCAL_SQL) {
config.orm.logger = {
// TODO: try to save SQL log into ctx logger or app logger
logQuery(sql: string, duration: number) {
console.log('[sql-debug] [%sms] %s', duration, sql);
},
};
}

config.redis = {
client: {
port: 6379,
host: '127.0.0.1',
password: '',
db: 0,
},
};

config.security = {
csrf: {
enable: false,
},
};

config.cors = {
// allow all domains
origin: (ctx): string => {
return ctx.get('Origin');
},
credentials: true,
};

config.nfs = {
client: null,
dir: join(config.dataDir, 'nfs'),
};
// enable oss nfs store by env values
if (process.env.CNPMCORE_NFS_TYPE === 'oss') {
assert(process.env.CNPMCORE_NFS_OSS_BUCKET, 'require env CNPMCORE_NFS_OSS_BUCKET');
assert(process.env.CNPMCORE_NFS_OSS_ENDPOINT, 'require env CNPMCORE_NFS_OSS_ENDPOINT');
assert(process.env.CNPMCORE_NFS_OSS_ID, 'require env CNPMCORE_NFS_OSS_ID');
assert(process.env.CNPMCORE_NFS_OSS_SECRET, 'require env CNPMCORE_NFS_OSS_SECRET');
config.nfs.client = new OSSClient({
cdnBaseUrl: process.env.CNPMCORE_NFS_OSS_CDN,
endpoint: process.env.CNPMCORE_NFS_OSS_ENDPOINT,
bucket: process.env.CNPMCORE_NFS_OSS_BUCKET,
accessKeyId: process.env.CNPMCORE_NFS_OSS_ID,
accessKeySecret: process.env.CNPMCORE_NFS_OSS_SECRET,
defaultHeaders: {
'Cache-Control': 'max-age=0, s-maxage=60',
},
});
}

config.logger = {
enablePerformanceTimer: true,
enableFastContextLogger: true,
};

config.logrotator = {
// only keep 1 days log files
maxDays: 1,
};

config.bodyParser = {
// saveTag will send version string in JSON format
strict: false,
// set default limit to 10mb, see https://github.com/npm/npm/issues/12750
jsonLimit: '10mb',
};

// https://github.com/xiekw2010/egg-typebox-validate#%E5%A6%82%E4%BD%95%E5%86%99%E8%87%AA%E5%AE%9A%E4%B9%89%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
config.typeboxValidate = { patchAjv };

config.httpclient = {
useHttpClientNext: true,
};
return config;

};
20 changes: 20 additions & 0 deletions hello-tegg/config/module.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[
{
"path": "../app/biz"
},
{
"path": "../app/infra"
},
{
"package": "cnpmcore/common"
},
{
"package": "cnpmcore/core"
},
{
"package": "cnpmcore/port"
},
{
"package": "cnpmcore/repository"
}
]
20 changes: 20 additions & 0 deletions hello-tegg/config/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,26 @@ const plugin: EggPlugin = {
enable: true,
package: '@eggjs/tegg-controller-plugin',
},
redis: {
enable: true,
package: 'egg-redis',
},
teggOrm: {
enable: true,
package: '@eggjs/tegg-orm-plugin',
},
eventbusModule: {
enable: true,
package: '@eggjs/tegg-eventbus-plugin',
},
tracer: {
enable: true,
package: 'egg-tracer',
},
typeboxValidate: {
enable: true,
package: 'egg-typebox-validate',
},
};

export default plugin;
4 changes: 3 additions & 1 deletion hello-tegg/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"clean": "tsc -b --clean"
},
"egg": {
"typescript": true
"typescript": true,
"declarations": true
},
"license": "MIT",
"dependencies": {
Expand All @@ -31,6 +32,7 @@
"devDependencies": {
"@types/mocha": "^10.0.1",
"@types/node": "^16.18.10",
"cnpmcore": "^3.5.0",
"egg-bin": "^6.0.0",
"egg-mock": "^5.4.0",
"eslint": "^8.30.0",
Expand Down
5 changes: 4 additions & 1 deletion hello-tegg/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
{
"extends": "@eggjs/tsconfig",
"compilerOptions": {
"baseUrl": "./"
"baseUrl": "./",
"moduleResolution": "NodeNext",
"target": "ES2020",
"module": "Node16"
}
}

0 comments on commit bed580f

Please sign in to comment.