1
1
/*
2
2
* @Author : Maslow<[email protected] >
3
3
* @Date : 2021-07-30 10:30:29
4
- * @LastEditTime : 2021-11-03 16:28:03
4
+ * @LastEditTime : 2021-11-09 19:09:30
5
5
* @Description :
6
6
*/
7
7
@@ -12,6 +12,7 @@ import { router } from './router/index'
12
12
import { logger } from './lib/logger'
13
13
import { generateUUID } from './lib/utils/rand'
14
14
import { initCloudSdkPackage } from './lib/utils/init'
15
+ import { WebSocketAgent } from './lib/ws'
15
16
16
17
initCloudSdkPackage ( )
17
18
@@ -20,9 +21,9 @@ initCloudSdkPackage()
20
21
*/
21
22
export * from './cloud-sdk'
22
23
23
- const server = express ( )
24
- server . use ( express . json ( ) as any )
25
- server . use ( express . urlencoded ( {
24
+ const app = express ( )
25
+ app . use ( express . json ( ) as any )
26
+ app . use ( express . urlencoded ( {
26
27
extended : true
27
28
} ) as any )
28
29
@@ -37,7 +38,7 @@ process.on('uncaughtException', err => {
37
38
/**
38
39
* Allow CORS by default
39
40
*/
40
- server . all ( '*' , function ( _req , res , next ) {
41
+ app . all ( '*' , function ( _req , res , next ) {
41
42
res . header ( 'Access-Control-Allow-Origin' , '*' )
42
43
res . header ( 'Access-Control-Allow-Headers' , 'Authorization, Content-Type' )
43
44
res . header ( 'Access-Control-Allow-Methods' , '*' )
@@ -48,7 +49,7 @@ server.all('*', function (_req, res, next) {
48
49
/**
49
50
* Parsing bearer token
50
51
*/
51
- server . use ( function ( req , res , next ) {
52
+ app . use ( function ( req , res , next ) {
52
53
const token = splitBearerToken ( req . headers [ 'authorization' ] ?? '' )
53
54
const auth = parseToken ( token ) || null
54
55
req [ 'auth' ] = auth
@@ -60,6 +61,16 @@ server.use(function (req, res, next) {
60
61
next ( )
61
62
} )
62
63
63
- server . use ( router )
64
+ app . use ( router )
65
+
66
+ const server = app . listen ( Config . PORT , ( ) => logger . info ( `server ${ process . pid } listened on ${ Config . PORT } ` ) )
67
+
68
+ /**
69
+ * WebSocket upgrade & connect
70
+ */
71
+ server . on ( 'upgrade' , ( req , socket , head ) => {
72
+ WebSocketAgent . server . handleUpgrade ( req , socket as any , head , ( client ) => {
73
+ WebSocketAgent . server . emit ( 'connection' , client , req )
74
+ } )
75
+ } )
64
76
65
- server . listen ( Config . PORT , ( ) => logger . info ( `server ${ process . pid } listened on ${ Config . PORT } ` ) )
0 commit comments