/* * @Description: * @version: * @Company: saganlab * @Author: vcbear * @Date: 2022-08-24 15:21:32 * @LastEditors: vcbear * @LastEditTime: 2022-11-28 09:57:17 */ import Koa from 'koa'; import path from 'path'; import { getHooks, deepMerge } from './utils' import { Hook, App, YiProcess } from './types'; const OAuth2 = require('oauth2-server') //const hooks = ['formData', 'log', 'proxy', 'mock', 'redis', 'mysql', 'elasticsearch', 'static', 'view', 'bodyparser', 'login', 'custom-middlewares', 'cors', 'router', 'lift']; const hooks = ['cors','formData', 'log', 'proxy', 'mock', 'redis', 'postgresql', 'mysql', 'elasticsearch', 'static', 'view', 'bodyparser', 'login', 'custom-middlewares', 'router', 'lift']; type Params = { appPath: string; oauthModel: any; } const dprocess = process as YiProcess; export default async function Yi(params: Params) { const app : App = (new Koa()) as App; const { appPath, oauthModel } = params; app.appPath = appPath; app.use(async (ctx, next)=> { ctx.set('Access-Control-Allow-Origin', '*'); ctx.set('Access-Control-Allow-Headers', 'Content-Type'); ctx.set('Access-Control-Allow-Methods', 'POST'); await next(); }); const oauth = new OAuth2({ model: oauthModel, allowBearerTokensInQueryString: true, accessTokenLifetime: 4 * 60 * 60, authenticateHandler: { handle: function(req) { // if (!req.user) { // throw new OAuthError('需要登录', { code: 400 }); // } return req; }, }, }) app.context.oauth = oauth; // 合并所有的配置项(基础+环境) const env = process.env.NODE_ENV; //const extName = app.extName = env === 'development' ? '.ts' : '.js'; const extName = app.extName = env === 'development' ? '.js' : '.js'; const baseConfig = await import(path.join(appPath, `config/config.base${extName}`)) const curConfig = await import(path.join(appPath, `config/config.${env}${extName}`)); app.config = deepMerge(baseConfig.default(app), curConfig.default(app)); // 获取所有的hook const allHooks: Hook[] = await getHooks(hooks); for (const hook of allHooks) { try { await hook.default(app); } catch (error) { dprocess.emit("error", error) } } // 错误捕获 app.on("error", error => { dprocess.emit("error", error) }); };