server.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. console.log(appConfig)
  31. global.config['DATABASE_DBNAME'] = process.env["DATABASE_DBNAME"] || appConfig["DATABASE_DBNAME"] || false
  32. global.config['DATABASE_LOCAL'] = process.env["DATABASE_LOCAL"] || appConfig["DATABASE_LOCAL"] || false
  33. global.config['MCENTER_ENABLED'] = process.env["MCENTER_ENABLED"] || appConfig["MCENTER_ENABLED"] || false
  34. global.config['PARSE_SERVERURL'] = process.env["PARSE_SERVERURL"] || appConfig["PARSE_SERVERURL"] || false
  35. global.config['PARSE_APPID'] = process.env["PARSE_APPID"] || appConfig["PARSE_APPID"] || false
  36. global.config['PARSE_MASTERKEY'] = process.env["PARSE_MASTERKEY"] || appConfig["PARSE_MASTERKEY"] || false
  37. global.config['SEGMENT_COUNT'] = process.env["SEGMENT_COUNT"] || appConfig["SEGMENT_COUNT"] || false
  38. global.config["LOCAL"] = argv.local || process.env["LOCAL"] || appConfig["LOCAL"] || global.config['DATABASE_LOCAL'] || false
  39. import {textbookRouter} from "./api/textbook/routes";
  40. import { defineAliOssSTS } from "./cloud/aliyun"
  41. import { defineAliSMSSend } from "./cloud/aliyun/func-aliyun-sms"
  42. import { defineAuthingLogin, defineDepartmentTrigger, defineUserAfterDelete, defineUserBeforeSave } from "./cloud/authing"
  43. import { defineAuthingDepartSync } from "./cloud/authing"
  44. import { defineUserAfterSave } from "./cloud/authing"
  45. import { defineTbookISBN } from "./cloud/tbook"
  46. import { defineTbookExportReport } from "./cloud/tbook/func-tbook-export"
  47. import { importData } from "./db/func/import-data"
  48. // 全局共享属性
  49. global.coolMap = {}
  50. global.minerMap = {}
  51. global.monitorMap = {}
  52. // Web服务启动器
  53. const express = require('express');
  54. const parse = require('parse-server')
  55. const Parse = require('parse/node')
  56. const ParseServer = parse.ParseServer;
  57. const ParseDashboard = require('parse-dashboard');
  58. // 同端口多进程集群
  59. let processCluster = require('cluster')
  60. let cpus = require('os').cpus()
  61. console.log(cpus.length)
  62. const app = express();
  63. const cors = require('cors');
  64. import { importAllSchemas } from "./db/func/import-schemas"
  65. import { PostgreSQLKeep } from "./lib/pg/index.js"
  66. app.use(cors({
  67. origin: '*'
  68. }));
  69. global.parseConfig = {
  70. port : 61337,
  71. allowClientClassCreation: true,
  72. allowExpiredAuthDataToken: false,
  73. encodeParseObjectInCloudFunction: false,
  74. }
  75. global.parseConfig.serverURL = `http://localhost:${global.parseConfig?.port}/parse`
  76. global.parseConfig.databaseURI = global.config['DATABASE_DBNAME'];
  77. if(global.config['LOCAL']) {
  78. global.parseConfig.databaseURI = "postgresql://postgres@127.0.0.1:25432/"
  79. }
  80. global.parseConfig.appId = 'edu-textbook'
  81. global.parseConfig.appName = 'EduParse'
  82. global.parseConfig.masterKey = 'EDU2024'
  83. // global.parseConfig.cloud = './cloud/main.js'
  84. Parse.initialize(global.parseConfig.appId,null,global.parseConfig.masterKey);
  85. Parse.serverURL = global.parseConfig.serverURL;
  86. async function startParse(){
  87. if(global.config['LOCAL']) {
  88. console.log("PostgreSQLKeep")
  89. await PostgreSQLKeep({username:"postgres",password:"postgres",port:"25432",dbpath:"database/edudata"
  90. })
  91. // await PostgreSQLKeep(global.config['DATABASE_DBNAME'], "database/edudata/" )
  92. }
  93. // 挂载微服务
  94. console.log(global.parseConfig)
  95. const api = new ParseServer(global.parseConfig);
  96. await api.start();
  97. // Serve the Parse API at /parse URL prefix
  98. app.use('/parse', api.app);
  99. // 挂载管理看板
  100. const dashboard = new ParseDashboard({
  101. "apps": [
  102. global.parseConfig
  103. ]
  104. }, { allowInsecureHTTP: true });
  105. app.use('/dashboard', dashboard);
  106. }
  107. process.on('exit', async () => {
  108. // await stopDB()
  109. });
  110. process.on('SIGINT', async () => {
  111. /* DO SOME STUFF HERE */
  112. // await stopDB()
  113. process.exit()
  114. })
  115. // 在程序中捕获异常并进行处理
  116. process.on('uncaughtException', async (err) => {
  117. console.error('Uncaught Exception:', err);
  118. process.exit(1);
  119. });
  120. // 启动服务
  121. async function initParseAndDatabase(){
  122. try{
  123. // 仅导入脚本参数
  124. if(argv.import){
  125. console.log("importAllSchemas")
  126. await importAllSchemas()
  127. return
  128. }
  129. console.log("正在启动微服务...")
  130. await startParse();
  131. // console.log("parse:",parseConfig)
  132. console.log("正在启动api接口")
  133. // 加载textbook专属路由 通过代理操控局域网设备
  134. app.use("/api/textbook",textbookRouter)
  135. app.get("/",(req,res)=>{
  136. res.json({
  137. code:200,
  138. data:{message:"ok"}
  139. })
  140. })
  141. /**
  142. * Listen on provided port, on all network interfaces.
  143. */
  144. app.listen(global.parseConfig?.port, async function() {
  145. console.log('微服务已运行,端口 ' + global.parseConfig?.port + '.');
  146. // 迁移数据范式 Schemas
  147. await importAllSchemas();
  148. // 导入初始化数据
  149. setTimeout(() => {
  150. importData()
  151. }, 500);
  152. // 导入CloudCode
  153. defineAuthingLogin();
  154. defineAuthingDepartSync();
  155. defineAliOssSTS();
  156. defineAliSMSSend();
  157. defineUserAfterSave();
  158. defineUserBeforeSave();
  159. defineUserAfterDelete();
  160. defineDepartmentTrigger();
  161. defineTbookISBN();
  162. defineTbookExportReport(app);
  163. });
  164. app.setTimeout(1000*300)
  165. console.log("正在启动管理看板...")
  166. console.log("浏览器管理看板:","http://localhost:61337/dashboard")
  167. }catch(err){
  168. console.error(err)
  169. }
  170. }
  171. // 启动服务端及数据库
  172. initParseAndDatabase()