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.

Utils.ts 3.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 {Errror} Error on RPC without name property
  10. */
  11. export const rpcToRpcinfo = <SubResT = {}>(rpc : T.RPC<SubResT>, owner: T.Owner):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>>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) => 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 Exporter}.
  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.Exporter<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. const hookGenerator = (rpc:T.HookRPC<any>): T.HookInfo['generator'] => {
  78. const argsArr = extractArgs(rpc.hook)
  79. argsArr.pop()
  80. const args = argsArr.join(',')
  81. return eval(`(socket) => async (`+args+`) => {
  82. const res = await rpc.hook(`+args+(args.length!==0?',':'')+` (...cbargs) => {
  83. if(rpc.onCallback) rpc.onCallback.apply({}, cbargs)
  84. socket.call.apply(socket, [res.uuid, ...cbargs])
  85. })
  86. if(res.result === 'Success'){
  87. if(rpc.onClose){
  88. socket.on('close', async () => {
  89. rpc.onClose(res, rpc)
  90. })
  91. }
  92. }
  93. return res
  94. }`)
  95. }
  96. const extractArgs = (f:Function):T.Arg[] => {
  97. let fn
  98. return (fn = String(f)).substr(0, fn.indexOf(")")).substr(fn.indexOf("(")+1).split(",")
  99. }
  100. export function makeSubResponse(uuid?:string):SubscriptionResponse{
  101. return {
  102. result: "Success",
  103. uuid: uuid?uuid:uuidv4(),
  104. }
  105. }