Browse Source

remove unhook

master
peter 5 years ago
parent
commit
759bb9c40f
6 changed files with 32 additions and 67 deletions
  1. 2
    2
      src/Backend.ts
  2. 1
    18
      src/Frontend.ts
  3. 10
    19
      src/Types.ts
  4. 8
    21
      src/Utils.ts
  5. 8
    4
      test/TestBackend.ts
  6. 3
    3
      test/TestFrontend.ts

+ 2
- 2
src/Backend.ts View File

27
         if(!conf.errorHandler) this.errorHandler = 
27
         if(!conf.errorHandler) this.errorHandler = 
28
         (socket:I.Socket) => (error:any) => { 
28
         (socket:I.Socket) => (error:any) => { 
29
             socket.destroy(); 
29
             socket.destroy(); 
30
-            console.error(error) 
30
+            console.error("Caught websocket error", String(error)) 
31
         }
31
         }
32
         
32
         
33
         if(!conf.closeHandler) this.closeHandler = 
33
         if(!conf.closeHandler) this.closeHandler = 
37
         
37
         
38
         if(!conf.connectionHandler) this.connectionHandler = 
38
         if(!conf.connectionHandler) this.connectionHandler = 
39
         (socket:I.Socket) => { 
39
         (socket:I.Socket) => { 
40
-            console.log("New websocket connection in port "+socket.port)
40
+            console.log("New websocket connection on port "+socket.port)
41
         }
41
         }
42
 
42
 
43
         let badRPC 
43
         let badRPC 

+ 1
- 18
src/Frontend.ts View File

58
                 case 'Hook':
58
                 case 'Hook':
59
                     f = this.hookGenerator(i.uniqueName, i.argNames)                    
59
                     f = this.hookGenerator(i.uniqueName, i.argNames)                    
60
                     break
60
                     break
61
-                case 'Unhook':
62
-                    f = this.unhookGenerator(i.uniqueName, i.argNames)                    
63
-                    break
64
             }
61
             }
65
             if(this[i.owner] == null)
62
             if(this[i.owner] == null)
66
                 this[i.owner] = {}
63
                 this[i.owner] = {}
79
         return eval( '( () => async ('+headerArgs+') => { return await this.socket.call("'+fnName+'", '+argParams+')} )()' )
76
         return eval( '( () => async ('+headerArgs+') => { return await this.socket.call("'+fnName+'", '+argParams+')} )()' )
80
     }
77
     }
81
 
78
 
82
-    private hookGenerator(fnName: T.Name, fnArgs:T.Arg[]): T.CallbackFunction{
79
+    private hookGenerator(fnName: T.Name, fnArgs:T.Arg[]): T.HookFunction{
83
         const headerArgs = fnArgs.join(",")
80
         const headerArgs = fnArgs.join(",")
84
         const argParams = fnArgs.map(stripAfterEquals).join(",")
81
         const argParams = fnArgs.map(stripAfterEquals).join(",")
85
         return eval( `( () => async (`+headerArgs+(headerArgs.length!==0?",":"")+` callback) => {
82
         return eval( `( () => async (`+headerArgs+(headerArgs.length!==0?",":"")+` callback) => {
90
                             return r
87
                             return r
91
                         } )()` )
88
                         } )()` )
92
     }
89
     }
93
-
94
-    private unhookGenerator(fnName: T.Name, fnArgs:T.Arg[]): T.UnhookFunction{
95
-        const headerArgs = fnArgs.join(",")
96
-        const argParams = fnArgs.map(stripAfterEquals).join(",")
97
-        if(fnArgs.length != 1)
98
-            console.error("UnhookFunction", fnName, "specified more than one argument: ("+headerArgs+")")
99
-
100
-        return eval( `( () => async (`+headerArgs+`) => {
101
-                            const r = await this.socket.call("`+fnName+`", `+argParams+`)
102
-                            this.socket.unhook(`+argParams+`)
103
-                            return r
104
-                        } )()` )
105
-    }
106
-
107
 }
90
 }

+ 10
- 19
src/Types.ts View File

25
 
25
 
26
 export type HookRPC = BaseRPC & {
26
 export type HookRPC = BaseRPC & {
27
     type: 'Hook'
27
     type: 'Hook'
28
-    hook: CallbackFunction
29
-    unhook: UnhookFunction
30
-}
31
-
32
-export type UnhookRPC = BaseRPC & {
33
-    type: 'Unhook'
34
-    unhook: UnhookFunction
28
+    hook: HookFunction
29
+    onCallback?: CallbackFunction,
30
+    onClose?: HookCloseFunction
35
 }
31
 }
36
 
32
 
37
 export type CallRPC = (BaseRPC & {
33
 export type CallRPC = (BaseRPC & {
39
     call: AsyncFunction
35
     call: AsyncFunction
40
 } ) | Function
36
 } ) | Function
41
 
37
 
42
-export type RPC = CallRPC | UnhookRPC | HookRPC
38
+export type RPC = CallRPC | HookRPC
43
 
39
 
44
 export type BaseInfo = {
40
 export type BaseInfo = {
45
     owner: Name,
41
     owner: Name,
48
 
44
 
49
 export type HookInfo = BaseRPC & BaseInfo & { 
45
 export type HookInfo = BaseRPC & BaseInfo & { 
50
     type: 'Hook', 
46
     type: 'Hook', 
51
-    generator: (socket) => CallbackFunction
52
-    unhook: UnhookFunction
53
-}
54
-
55
-export type UnhookInfo = BaseRPC & BaseInfo & {
56
-    type: 'Unhook',
57
-    unhook: UnhookFunction
47
+    generator: (socket) => HookFunction
58
 }
48
 }
59
 
49
 
60
 export type CallInfo = BaseRPC & BaseInfo & {
50
 export type CallInfo = BaseRPC & BaseInfo & {
62
     call: AsyncFunction
52
     call: AsyncFunction
63
 }
53
 }
64
 
54
 
65
-export type RpcInfo = HookInfo | UnhookInfo | CallInfo
55
+export type RpcInfo = HookInfo |  CallInfo
66
 export type ExtendedRpcInfo = RpcInfo & { uniqueName: string } 
56
 export type ExtendedRpcInfo = RpcInfo & { uniqueName: string } 
67
 
57
 
68
 export type OnFunction = (type: 'error' | 'close', f: (e?:any)=>void) => I.Socket
58
 export type OnFunction = (type: 'error' | 'close', f: (e?:any)=>void) => I.Socket
69
-export type UnhookFunction = (uid:string) => Promise<R.SuccessResponse | R.ErrorResponse>
70
-export type CallbackFunction = (...args) => Promise<R.SubscriptionResponse | R.ErrorResponse>
71
-export type AsyncFunction = (...args) => Promise<any>
59
+export type HookCloseFunction = (res:R.SubscriptionResponse) => any
60
+export type HookFunction = (...args:any[]) => Promise<R.SubscriptionResponse | R.ErrorResponse>
61
+export type AsyncFunction = (...args:any[]) => Promise<any>
62
+export type CallbackFunction = (arg: any) => void

+ 8
- 21
src/Utils.ts View File

15
                     name: rpc.name,
15
                     name: rpc.name,
16
                     call: rpc.call,
16
                     call: rpc.call,
17
                 }
17
                 }
18
-            case "Unhook" :
19
-                return {
20
-                    owner: owner,
21
-                    argNames: extractArgs(rpc.unhook),
22
-                    type: rpc.type,
23
-                    name: rpc.name,
24
-                    unhook: rpc.unhook,
25
-                }
26
             case "Hook" :
18
             case "Hook" :
27
                 const generator = hookGenerator(rpc)
19
                 const generator = hookGenerator(rpc)
28
                 return {
20
                 return {
30
                     argNames: extractArgs(generator(undefined)),
22
                     argNames: extractArgs(generator(undefined)),
31
                     type: rpc.type,
23
                     type: rpc.type,
32
                     name: rpc.name,
24
                     name: rpc.name,
33
-                    unhook: rpc.unhook,
34
                     generator: generator,
25
                     generator: generator,
26
+                    
35
                 }
27
                 }
36
         }
28
         }
37
         break;
29
         break;
67
             case "Hook":
59
             case "Hook":
68
                 socket.hook(ret.uniqueName, info.generator(socket))
60
                 socket.hook(ret.uniqueName, info.generator(socket))
69
                 break;
61
                 break;
70
-            case "Unhook":
71
-                socket.hook(ret.uniqueName, info.unhook)
72
-                break;
73
             case "Call":
62
             case "Call":
74
                 socket.hook(ret.uniqueName, info.call)
63
                 socket.hook(ret.uniqueName, info.call)
75
                 break;
64
                 break;
85
     const args = argsArr.join(',')
74
     const args = argsArr.join(',')
86
 
75
 
87
     return eval(`(socket) => async (`+args+`) => { 
76
     return eval(`(socket) => async (`+args+`) => { 
88
-        const res = await rpc.hook(`+args+(args.length!==0?',':'')+` (x) => {
89
-            socket.call(res.uid, x)
77
+        const res = await rpc.hook(`+args+(args.length!==0?',':'')+` (...cbargs) => {
78
+            if(rpc.onCallback) rpc.onCallback.apply({}, cbargs)
79
+            socket.call.apply(socket, [res.uid, ...cbargs])
90
         })
80
         })
91
         if(res.result == 'Success'){
81
         if(res.result == 'Success'){
82
+            if(rpc.onClose)
92
             socket.on('close', async () => {
83
             socket.on('close', async () => {
93
-                const unhookRes = await rpc.unhook(res.uid)
94
-                console.log("Specific close handler for", rpc.name, res.uid, unhookRes)
84
+                rpc.onClose(res)
95
             })
85
             })
96
         }
86
         }
97
         return res
87
         return res
99
 }
89
 }
100
 
90
 
101
 const extractArgs = (f:Function):T.Arg[] => {
91
 const extractArgs = (f:Function):T.Arg[] => {
102
-    let fn = String(f)
103
-    let args = fn.substr(0, fn.indexOf(")"))
104
-    args = args.substr(fn.indexOf("(")+1)
105
-    let ret = args.split(",")
106
-    return ret
92
+    let fn
93
+    return (fn = String(f)).substr(0, fn.indexOf(")")).substr(fn.indexOf("(")+1).split(",")
107
 }
94
 }

+ 8
- 4
test/TestBackend.ts View File

1
 import { RPCServer } from '../src/Backend'
1
 import { RPCServer } from '../src/Backend'
2
-import { SubscriptionResponse } from '../src/Responses'
2
+import { SubscriptionResponse, ErrorResponse, SuccessResponse } from '../src/Responses'
3
+import { HookRPC } from '../src/Types'
3
 
4
 
4
 let subcallback
5
 let subcallback
5
 
6
 
17
             subcallback = callback
18
             subcallback = callback
18
             return new SubscriptionResponse(""+Math.random())
19
             return new SubscriptionResponse(""+Math.random())
19
         },
20
         },
20
-        unhook: async (uid):Promise<any> => { subcallback = null }
21
+        onClose: (res:SubscriptionResponse) => { 
22
+            console.log("Specific close handler for", res)
23
+            subcallback = null 
24
+        }
21
     },
25
     },
22
     function add(...args:number[]):number {return args.reduce((a,b)=>a+b, 0)},
26
     function add(...args:number[]):number {return args.reduce((a,b)=>a+b, 0)},
23
-    function triggerCallback(message):number {return subcallback(message)},
27
+    function triggerCallback(...messages:any[]):number {return subcallback.apply({}, messages)},
24
 ]
28
 ]
25
 }])
29
 }])
26
 
30
 
32
         ]
36
         ]
33
     }])
37
     }])
34
 }catch(badRPCError){
38
 }catch(badRPCError){
35
-    console.log("expected bad-RPC error happened: "+ !!badRPCError)
39
+    console.log("expected bad-RPC error happened: "+ !!badRPCError, String(badRPCError))
36
 }
40
 }

+ 3
- 3
test/TestFrontend.ts View File

17
     }
17
     }
18
 
18
 
19
     await client["HelloWorldRPCGroup"].subscribe(handler)
19
     await client["HelloWorldRPCGroup"].subscribe(handler)
20
-    client["HelloWorldRPCGroup"].triggerCallback("test1")
21
-    client["HelloWorldRPCGroup"].triggerCallback("test2")
22
-    client["HelloWorldRPCGroup"].triggerCallback("test3")
20
+    client["HelloWorldRPCGroup"].triggerCallback("test1", "test1", "test1", )
21
+    client["HelloWorldRPCGroup"].triggerCallback("test2", "test2", "test2", )
22
+    client["HelloWorldRPCGroup"].triggerCallback("test3", "test3", "test3", )
23
 })
23
 })

Loading…
Cancel
Save