You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import * as uuidv4 from "uuid/v4"
  2. import * as T from "./Types";
  3. import * as I from "./Interfaces";
  4. import { SubscriptionResponse } from "./Types";
  5. /**
  6. * Translate an RPC to RPCInfo for serialization.
  7. * @param rpc The RPC to transform
  8. * @param owner The owning RPC group's name
  9. * @throws Error on RPC without name property
  10. */
  11. export const rpcToRpcinfo = <SubResT = {}>(rpc : T.RPC<any, any, SubResT>, owner: string):T.RpcInfo => {
  12. switch (typeof rpc){
  13. case "object":
  14. if(rpc['call']){
  15. return {
  16. owner: owner,
  17. argNames: extractArgs(rpc['call']),
  18. type: "Call",
  19. name: rpc.name,
  20. call: rpc['call'],
  21. }
  22. }else{
  23. const generator = hookGenerator(<T.HookRPC<any, any, any>>rpc)
  24. return {
  25. owner: owner,
  26. argNames: extractArgs(generator(undefined)),
  27. type: "Hook",
  28. name: rpc.name,
  29. generator: generator,
  30. }
  31. }
  32. case "function":
  33. if(!rpc.name) throw new Error(`
  34. RPC did not provide a name.
  35. \nUse 'funtion name(..){ .. }' syntax instead.
  36. \n
  37. \n<------------OFFENDING RPC:
  38. \n`+rpc.toString()+`
  39. \n>------------OFFENDING RPC`)
  40. return {
  41. owner : owner,
  42. argNames: extractArgs(rpc),
  43. type: "Call",
  44. name: rpc.name,
  45. call: async(...args) => (<Function>rpc).apply({}, args),
  46. }
  47. }
  48. throw new Error("Bad socketIORPC type "+ typeof rpc)
  49. }
  50. /**
  51. * Utility function to apply the RPCs of an {@link RPCExporter}.
  52. * @param socket The websocket (implementation: bsock) to hook on
  53. * @param exporter The exporter
  54. * @param makeUnique @default true Attach a suffix to RPC names
  55. */
  56. export function rpcHooker<SubResT = {}>(socket: I.Socket, exporter:I.RPCExporter<any, any, SubResT>, makeUnique = true):T.ExtendedRpcInfo[]{
  57. const owner = exporter.name
  58. const RPCs = [...exporter.exportRPCs()]
  59. const suffix = makeUnique?"-"+uuidv4().substr(0,4):""
  60. return RPCs.map(rpc => rpcToRpcinfo(rpc, owner))
  61. .map(info => {
  62. const ret:any = info
  63. ret.uniqueName = info.name+suffix
  64. switch(info.type){
  65. case "Hook":
  66. socket.hook(ret.uniqueName, info.generator(socket))
  67. break;
  68. case "Call":
  69. socket.hook(ret.uniqueName, info.call)
  70. break;
  71. }
  72. socket.on('close', () => socket.unhook(info.name))
  73. return ret
  74. })
  75. }
  76. /**
  77. * Utility function to generate {@link HookFunction} from a RPC
  78. * @param rpc The RPC to transform
  79. * @returns A {@link HookFunction}
  80. */
  81. const hookGenerator = (rpc:T.HookRPC<any, any, any>): T.HookInfo['generator'] => {
  82. const argsArr = extractArgs(rpc.hook)
  83. argsArr.pop()
  84. const args = argsArr.join(',')
  85. return eval(`(socket) => async (`+args+`) => {
  86. const res = await rpc.hook(`+args+(args.length!==0?',':'')+` (...cbargs) => {
  87. if(rpc.onCallback) rpc.onCallback.apply({}, cbargs)
  88. socket.call.apply(socket, [res.uuid, ...cbargs])
  89. })
  90. if(res.result === 'Success'){
  91. if(rpc.onClose){
  92. socket.on('close', async () => {
  93. rpc.onClose(res, rpc)
  94. })
  95. }
  96. }
  97. return res
  98. }`)
  99. }
  100. /**
  101. * Extract a string list of parameters from a function
  102. * @param f The source function
  103. */
  104. const extractArgs = (f:Function):string[] => {
  105. let fn:string
  106. return (fn = String(f)).substr(0, fn.indexOf(")")).substr(fn.indexOf("(")+1).split(",")
  107. }
  108. /**
  109. * Simple utility function to create basic {@link SubscriptionResponse}
  110. * @param uuid optional uuid to use, otherwise defaults to uuid/v4
  111. */
  112. export function makeSubResponse<T extends {} = {}>(extension:T):SubscriptionResponse & T{
  113. return {
  114. result: "Success",
  115. uuid: uuidv4(),
  116. ...extension
  117. }
  118. }