run_app.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // 导入所需模块
  2. import { Hono } from 'hono'
  3. import { APIClient } from '@d8d-appcontainer/api'
  4. import debug from "debug"
  5. import { cors } from 'hono/cors'
  6. // 初始化debug实例
  7. const log = {
  8. app: debug('app:server'),
  9. auth: debug('auth:server'),
  10. api: debug('api:server'),
  11. debug: debug('debug:server')
  12. }
  13. // 启用所有日志
  14. Object.values(log).forEach(logger => logger.enabled = true)
  15. // 初始化 API Client
  16. const getApiClient = async (workspaceKey: string, serverUrl?: string) => {
  17. try {
  18. log.api('正在初始化API Client实例')
  19. const apiClient = await APIClient.getInstance({
  20. scope: 'user',
  21. config: {
  22. serverUrl: serverUrl || Deno.env.get('SERVER_URL') || 'https://app-server.d8d.fun',
  23. workspaceKey: workspaceKey,
  24. type: 'http',
  25. }
  26. })
  27. log.api('API Client初始化成功')
  28. return apiClient
  29. } catch (error) {
  30. log.api('API Client初始化失败:', error)
  31. throw error
  32. }
  33. }
  34. // 创建Hono应用实例
  35. const app = new Hono()
  36. // 注册CORS中间件
  37. app.use('/*', cors())
  38. // 动态加载并运行模板
  39. const runTemplate = async () => {
  40. try {
  41. // 创建基础app实例
  42. const moduleApp = new Hono()
  43. // 初始化API Client
  44. // 注意:WORKSPACE_KEY 需要在 多八多(www.d8d.fun) 平台注册并开通工作空间后获取
  45. const workspaceKey = Deno.env.get('WORKSPACE_KEY') || ''
  46. if (!workspaceKey) {
  47. console.warn('未设置WORKSPACE_KEY,请前往 多八多(www.d8d.fun) 注册并开通工作空间以获取密钥')
  48. }
  49. const apiClient = await getApiClient(workspaceKey)
  50. // 导入模板主模块
  51. const templateModule = await import('./app.tsx')
  52. if (templateModule.default) {
  53. // 传入必要参数并初始化应用
  54. const appInstance = templateModule.default({
  55. apiClient: apiClient,
  56. app: moduleApp,
  57. moduleDir: './'
  58. })
  59. // 启动服务器
  60. Deno.serve({ port: 8080 }, appInstance.fetch)
  61. console.log('应用已启动,监听端口: 8080')
  62. }
  63. } catch (error) {
  64. console.error('模板加载失败:', error)
  65. }
  66. }
  67. // 执行模板
  68. runTemplate()