3
3
const http = require ( 'node:http' ) ;
4
4
const console = require ( './logger.js' ) ;
5
5
6
+ const answerNotFound = ( res , headers ) => {
7
+ res . writeHead ( 404 , headers ) ;
8
+ res . end ( 'Not found' ) ;
9
+ } ;
10
+
6
11
const receiveArgs = async ( req ) => {
7
12
const buffers = [ ] ;
8
13
for await ( const chunk of req ) buffers . push ( chunk ) ;
@@ -11,22 +16,34 @@ const receiveArgs = async (req) => {
11
16
} ;
12
17
13
18
module . exports = ( routing , port ) => {
14
- http . createServer ( async ( req , res ) => {
15
- const { url, socket } = req ;
16
- const [ name , method , id ] = url . substring ( 1 ) . split ( '/' ) ;
17
- const entity = routing [ name ] ;
18
- if ( ! entity ) return void res . end ( 'Not found' ) ;
19
- const handler = entity [ method ] ;
20
- if ( ! handler ) return void res . end ( 'Not found' ) ;
21
- const src = handler . toString ( ) ;
22
- const signature = src . substring ( 0 , src . indexOf ( ')' ) ) ;
23
- const args = [ ] ;
24
- if ( signature . includes ( '(id' ) ) args . push ( id ) ;
25
- if ( signature . includes ( '{' ) ) args . push ( await receiveArgs ( req ) ) ;
26
- console . log ( `${ socket . remoteAddress } ${ method } ${ url } ` ) ;
27
- const result = await handler ( ...args ) ;
28
- res . end ( JSON . stringify ( result . rows ) ) ;
29
- } ) . listen ( port ) ;
19
+ http
20
+ . createServer ( async ( req , res ) => {
21
+ const headers = {
22
+ 'Access-Control-Allow-Origin' :
23
+ '*' /* @dev First, read about security */ ,
24
+ 'Access-Control-Allow-Methods' : 'POST' ,
25
+ 'Access-Control-Max-Age' : 2592000 , // 30 days
26
+ /** add other headers as per requirement */
27
+ } ;
28
+
29
+ const { url, socket } = req ;
30
+ const [ name , method , id ] = url . substring ( 1 ) . split ( '/' ) ;
31
+ const entity = routing [ name ] ;
32
+ if ( ! entity ) return void answerNotFound ( res , headers ) ;
33
+ const handler = entity [ method ] ;
34
+ if ( ! handler ) return void answerNotFound ( res , headers ) ;
35
+
36
+ res . writeHead ( 200 , headers ) ;
37
+ const src = handler . toString ( ) ;
38
+ const signature = src . substring ( 0 , src . indexOf ( ')' ) ) ;
39
+ const args = [ ] ;
40
+ if ( signature . includes ( '(id' ) ) args . push ( id ) ;
41
+ args . push ( ...( await receiveArgs ( req ) ) ) ;
42
+ console . log ( `${ socket . remoteAddress } ${ req . method } ${ url } ` ) ;
43
+ const result = await handler ( ...args ) ;
44
+ res . end ( JSON . stringify ( result . rows ) ) ;
45
+ } )
46
+ . listen ( port ) ;
30
47
31
48
console . log ( `API on port ${ port } ` ) ;
32
49
} ;
0 commit comments