server.js 5.1 KB

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