server.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. // 数据库启动器
  2. const path = require("path")
  3. const fs = require("fs")
  4. // 全局配置加载
  5. // IMPORTANT:通过apps/<appId>/加载应用独立配置
  6. var appConfig
  7. try{
  8. appConfig = require(`./config.js`) // 默认加载包内config.js文件
  9. }catch{}
  10. if(!appConfig) appConfig = {}
  11. var userConfig
  12. /*********************
  13. * windows: process.env.PORTABLE_EXECUTABLE_DIR
  14. * linux: process.env.OWD
  15. */
  16. var OWN_DIR = process.env.PORTABLE_EXECUTABLE_DIR || process.env.OWD || process.cwd() || __dirname
  17. if (OWN_DIR) {
  18. let configPath = path.join(OWN_DIR, `config.js`)
  19. if (fs.existsSync(configPath)) {
  20. userConfig = require(configPath) // 用户独立配置config.js覆盖
  21. if (userConfig) {
  22. Object.keys(userConfig).forEach(key => {
  23. appConfig[key] = userConfig[key]
  24. })
  25. }
  26. }
  27. }
  28. global.config = global.config || {}
  29. global.config['DATABASE_LOCAL'] = process.env["DATABASE_LOCAL"] || appConfig["DATABASE_LOCAL"] || false
  30. global.config['MCENTER_ENABLED'] = process.env["MCENTER_ENABLED"] || appConfig["MCENTER_ENABLED"] || false
  31. global.config['PARSE_SERVERURL'] = process.env["PARSE_SERVERURL"] || appConfig["PARSE_SERVERURL"] || false
  32. global.config['PARSE_APPID'] = process.env["PARSE_APPID"] || appConfig["PARSE_APPID"] || false
  33. global.config['PARSE_MASTERKEY'] = process.env["PARSE_MASTERKEY"] || appConfig["PARSE_MASTERKEY"] || false
  34. global.config['SEGMENT_COUNT'] = process.env["SEGMENT_COUNT"] || appConfig["SEGMENT_COUNT"] || false
  35. // 全局共享属性
  36. global.coolMap = {}
  37. global.minerMap = {}
  38. global.monitorMap = {}
  39. // Web服务启动器
  40. const express = require('express');
  41. const parse = require('parse-server')
  42. const Parse = require('parse/node')
  43. const ParseServer = parse.ParseServer;
  44. const ParseDashboard = require('parse-dashboard');
  45. // 同端口多进程集群
  46. let processCluster = require('cluster')
  47. let cpus = require('os').cpus()
  48. console.log(cpus.length)
  49. const app = express();
  50. const cors = require('cors');
  51. const { importAllSchemas } = require("./db/func/import-schemas")
  52. const { PostgreSQLKeep } = require("./lib/pg/index.js")
  53. app.use(cors({
  54. origin: '*'
  55. }));
  56. global.parseConfig = {
  57. port : 61337,
  58. allowClientClassCreation: true,
  59. allowExpiredAuthDataToken: false,
  60. encodeParseObjectInCloudFunction: false,
  61. }
  62. global.parseConfig.serverURL = `http://localhost:${global.parseConfig?.port}/parse`
  63. global.parseConfig.databaseURI = "postgresql://postgres@127.0.0.1:25432/"
  64. if(global.config['DATABASE_LOCAL']) {
  65. global.parseConfig.databaseURI = "postgresql://postgres@127.0.0.1:25432/"
  66. }
  67. global.parseConfig.appId = 'edu-textbook'
  68. global.parseConfig.appName = 'EduParse'
  69. global.parseConfig.masterKey = 'EDU2024'
  70. global.parseConfig.cloud = './cloud/main.js'
  71. Parse.initialize(global.parseConfig.appId,null,global.parseConfig.masterKey);
  72. Parse.serverURL = global.parseConfig.serverURL;
  73. async function startParse(){
  74. if(global.config['DATABASE_LOCAL']) {
  75. await PostgreSQLKeep({
  76. username:"postgres",
  77. password:"postgres",
  78. port:"25432",
  79. dbpath:"database/edudata"
  80. })
  81. }
  82. // 挂载微服务
  83. const api = new ParseServer(global.parseConfig);
  84. await api.start();
  85. // Serve the Parse API at /parse URL prefix
  86. app.use('/parse', api.app);
  87. // 挂载管理看板
  88. const dashboard = new ParseDashboard({
  89. "apps": [
  90. global.parseConfig
  91. ]
  92. }, { allowInsecureHTTP: true });
  93. app.use('/dashboard', dashboard);
  94. }
  95. process.on('exit', async () => {
  96. // await stopDB()
  97. });
  98. process.on('SIGINT', async () => {
  99. /* DO SOME STUFF HERE */
  100. // await stopDB()
  101. process.exit()
  102. })
  103. // 在程序中捕获异常并进行处理
  104. process.on('uncaughtException', async (err) => {
  105. console.error('Uncaught Exception:', err);
  106. process.exit(1);
  107. });
  108. // 启动服务
  109. async function initParseAndDatabase(){
  110. try{
  111. console.log("正在启动微服务...")
  112. await startParse();
  113. // console.log("parse:",parseConfig)
  114. console.log("正在启动api接口")
  115. // 加载textbook专属路由 通过代理操控局域网设备
  116. let textbookRouter = require("./api/textbook/routes")
  117. app.use("/api/textbook",textbookRouter)
  118. app.get("/",(req,res)=>{
  119. res.json({
  120. code:200,
  121. data:{message:"ok"}
  122. })
  123. })
  124. /**
  125. * Listen on provided port, on all network interfaces.
  126. */
  127. app.listen(global.parseConfig?.port, async function() {
  128. console.log('微服务已运行,端口 ' + global.parseConfig?.port + '.');
  129. // 迁移数据范式 Schemas
  130. await importAllSchemas();
  131. // 导入初始化数据
  132. setTimeout(() => {
  133. require("./db/func/import-data")
  134. }, 500);
  135. });
  136. console.log("正在启动管理看板...")
  137. console.log("浏览器管理看板:","http://localhost:61337/dashboard")
  138. }catch(err){
  139. console.error(err)
  140. }
  141. }
  142. // 启动服务端及数据库
  143. initParseAndDatabase()