支持自定义的endpoint

This commit is contained in:
Pan Qiancheng 2025-04-15 09:27:56 +08:00
parent 7d465f87c3
commit 51cb5d36fd
3 changed files with 21 additions and 32 deletions

View File

@ -1,4 +1,3 @@
/// <reference path="../../src/typings/polyfill.d.ts" />
import './polyfill'; import './polyfill';
import { BackendRuntimeContext } from 'oak-frontend-base/lib/context/BackendRuntimeContext'; import { BackendRuntimeContext } from 'oak-frontend-base/lib/context/BackendRuntimeContext';
import { Connector, EntityDict } from 'oak-domain/lib/types'; import { Connector, EntityDict } from 'oak-domain/lib/types';

View File

@ -1,6 +1,6 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.startup = void 0; exports.startup = startup;
const tslib_1 = require("tslib"); const tslib_1 = require("tslib");
/// <reference path="../typings/polyfill.d.ts" /> /// <reference path="../typings/polyfill.d.ts" />
require("./polyfill"); require("./polyfill");
@ -55,7 +55,7 @@ async function startup(path, connector, omitWatchers, omitTimers, routine) {
} }
: serverConfiguration.cors : serverConfiguration.cors
? { ? {
origin: serverConfiguration.cors.origin, origin: serverConfiguration.cors.origin, //socket.io配置cors origin是支持数组和字符串
allowedHeaders: [ allowedHeaders: [
...corsHeaders.concat(connector.getCorsHeader()), ...corsHeaders.concat(connector.getCorsHeader()),
...(serverConfiguration.cors.headers || []), ...(serverConfiguration.cors.headers || []),
@ -259,18 +259,13 @@ async function startup(path, connector, omitWatchers, omitTimers, routine) {
}); });
// 注入所有的endpoints // 注入所有的endpoints
const endpoints = appLoader.getEndpoints(connector.getEndpointRouter()); const endpoints = appLoader.getEndpoints(connector.getEndpointRouter());
endpoints.forEach(([name, method, url, fn]) => { endpoints.forEach(([type, name, method, url, fn]) => {
router[method](url, async (ctx) => { router[method](url, async (ctx) => {
const { req, request, params } = ctx;
const { body, headers, files } = request;
try { try {
const result = await fn(params, headers, req, files ? Object.assign({}, body, files) : body); await fn(ctx);
ctx.response.body = result;
return;
} }
catch (err) { catch (err) {
ctx.response.status = 500; console.log("exec:", name, "occure a error: ", err);
return;
} }
}); });
}); });
@ -302,4 +297,3 @@ async function startup(path, connector, omitWatchers, omitTimers, routine) {
}; };
return shutdown; return shutdown;
} }
exports.startup = startup;

View File

@ -42,7 +42,7 @@ export async function startup<ED extends EntityDict & BaseEntityDict, FrontCxt e
omitWatchers?: boolean, omitWatchers?: boolean,
omitTimers?: boolean, omitTimers?: boolean,
routine?: (context: AsyncContext<ED>) => Promise<void>, routine?: (context: AsyncContext<ED>) => Promise<void>,
): Promise<(() => Promise<void> )| undefined> { ): Promise<(() => Promise<void>) | undefined> {
const serverConfiguration: ServerConfiguration = require(join( const serverConfiguration: ServerConfiguration = require(join(
path, path,
'lib', 'lib',
@ -68,11 +68,11 @@ export async function startup<ED extends EntityDict & BaseEntityDict, FrontCxt e
const socketOption: Partial<ServerOptions> = { const socketOption: Partial<ServerOptions> = {
path: connector.getSocketPath(), path: connector.getSocketPath(),
cors: ['development', 'staging'].includes(process.env.NODE_ENV!) cors: ['development', 'staging'].includes(process.env.NODE_ENV!)
? { ? {
origin: '*', origin: '*',
allowedHeaders: corsHeaders.concat(connector.getCorsHeader()), allowedHeaders: corsHeaders.concat(connector.getCorsHeader()),
} }
: serverConfiguration.cors : serverConfiguration.cors
? { ? {
origin: serverConfiguration.cors.origin, //socket.io配置cors origin是支持数组和字符串 origin: serverConfiguration.cors.origin, //socket.io配置cors origin是支持数组和字符串
allowedHeaders: [ allowedHeaders: [
@ -102,15 +102,15 @@ export async function startup<ED extends EntityDict & BaseEntityDict, FrontCxt e
} }
const isCluster = Array.isArray(redisConfig); const isCluster = Array.isArray(redisConfig);
// 创建 Redis 客户端 // 创建 Redis 客户端
const pubClient = isCluster ? const pubClient = isCluster ?
new Redis.Cluster(redisConfig.map((config) => ({ new Redis.Cluster(redisConfig.map((config) => ({
...config, ...config,
lazyConnect: true, lazyConnect: true,
}))) })))
: new Redis({ : new Redis({
...redisConfig, ...redisConfig,
lazyConnect: true, lazyConnect: true,
}); });
const subClient = pubClient.duplicate(); const subClient = pubClient.duplicate();
pubClient.on('connect', () => { pubClient.on('connect', () => {
console.log('PUB已成功连接到Redis服务器'); console.log('PUB已成功连接到Redis服务器');
@ -156,7 +156,7 @@ export async function startup<ED extends EntityDict & BaseEntityDict, FrontCxt e
const appLoader = clusterInfo.usingCluster const appLoader = clusterInfo.usingCluster
? new ClusterAppLoader<ED, Cxt>( ? new ClusterAppLoader<ED, Cxt>(
path, path,
io.of(DATA_SUBSCRIBE_NAMESPACE ), io.of(DATA_SUBSCRIBE_NAMESPACE),
io.of(SOCKET_NAMESPACE), io.of(SOCKET_NAMESPACE),
io.of(SERVER_SUBSCRIBER_NAMESPACE), io.of(SERVER_SUBSCRIBER_NAMESPACE),
connector.getSocketPath() connector.getSocketPath()
@ -329,17 +329,13 @@ export async function startup<ED extends EntityDict & BaseEntityDict, FrontCxt e
// 注入所有的endpoints // 注入所有的endpoints
const endpoints = appLoader.getEndpoints(connector.getEndpointRouter()); const endpoints = appLoader.getEndpoints(connector.getEndpointRouter());
endpoints.forEach(([name, method, url, fn]) => { endpoints.forEach(([type, name, method, url, fn]) => {
router[method](url, async (ctx) => { router[method](url, async (ctx) => {
const { req, request, params } = ctx;
const { body, headers, files } = request;
try { try {
const result = await fn(params, headers, req, files ? Object.assign({}, body, files) : body); await fn(ctx);
ctx.response.body = result;
return;
} catch (err) { } catch (err) {
ctx.response.status = 500; console.log("exec:", name , "occure a error: ", err);
return;
} }
}); });
}); });