Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

Frontend.ts 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. 'use strict'
  2. import { PromiseIOClient } from './PromiseIO/Client'
  3. import * as T from './Types';
  4. import * as I from './Interfaces';
  5. import { stripAfterEquals, appendComma } from './Utils';
  6. /**
  7. * A websocket-on-steroids with built-in RPC capabilities
  8. */
  9. export class RPCSocket<Ifc extends T.RPCInterface = T.RPCInterface> implements I.Socket{
  10. static async makeSocket<T extends T.RPCInterface = T.RPCInterface>(port:number, server: string, sesame?:string, conf?:T.SocketConf): Promise<T.ConnectedSocket<T>> {
  11. const socket = new RPCSocket<T>(port, server, conf)
  12. return await socket.connect(sesame)
  13. }
  14. private protocol: 'http:' | 'https:'
  15. private socket: I.Socket
  16. private handlers : {
  17. [name in string]: T.AnyFunction[]
  18. } = {
  19. error: [],
  20. close: []
  21. }
  22. private hooks : {[name in string]: T.AnyFunction} = {}
  23. /**
  24. *
  25. * @param port Port to connect to
  26. * @param server Server address
  27. * @param tls @default false use TLS
  28. */
  29. constructor(public port:number, private server: string, conf:T.SocketConf = { tls: false }){
  30. Object.defineProperty(this, 'socket', {value: undefined, writable: true})
  31. this.protocol = conf.tls ? "https:" : "http:"
  32. }
  33. /**
  34. * Hooks a handler to a function name. Use {@link call} to trigger it.
  35. * @param name The function name to listen on
  36. * @param handler The handler to attach
  37. */
  38. public hook(name: string, handler: (...args:any[]) => any | Promise<any>){
  39. if(!this.socket){
  40. this.hooks[name] = handler
  41. }else{
  42. this.socket.hook(name, handler)
  43. }
  44. }
  45. /**
  46. * Hooks a handler to a function name. Use {@link call} to trigger it.
  47. * @param name The function name to listen on
  48. * @param handler The handler to attach
  49. */
  50. public bind(name: string, handler: (...args:any[]) => any | Promise<any>){
  51. if(!this.socket){
  52. this.hooks[name] = handler
  53. }else{
  54. this.socket.bind(name, handler)
  55. }
  56. }
  57. /**
  58. * Removes a {@link hook} listener by name.
  59. * @param name The function name
  60. */
  61. public unhook(name: string){
  62. if(!this.socket){
  63. delete this.hooks[name]
  64. }else{
  65. this.socket.unhook(name)
  66. }
  67. }
  68. /**
  69. * Attach a listener to error or close events
  70. * @param type 'error' or 'close'
  71. * @param f The listener to attach
  72. */
  73. public on(type: string, f: T.AnyFunction){
  74. if(!this.socket){
  75. if(!this.handlers[type])
  76. this.handlers[type] = []
  77. this.handlers[type].push(f)
  78. }else{
  79. this.socket.on(type, f)
  80. }
  81. }
  82. /**
  83. * Emit a LOCAL event
  84. * @param eventName The event name to emit under
  85. * @param data The data the event carries
  86. */
  87. public emit(eventName:string, data:any){
  88. if(!this.socket) return
  89. this.socket.emit(eventName, data)
  90. }
  91. /**
  92. * Closes the socket. It may attempt to reconnect.
  93. */
  94. public close(){
  95. if(!this.socket) return;
  96. this.socket.close()
  97. }
  98. /**
  99. * Trigger a hooked handler on the server
  100. * @param rpcname The function to call
  101. * @param args other arguments
  102. */
  103. public async call (rpcname: string, ...args: any[]) : Promise<any>{
  104. if(!this.socket) throw new Error("The socket is not connected! Use socket.connect() first")
  105. try{
  106. const val = await this.socket.call.apply(this.socket, [rpcname, ...args])
  107. return val
  108. }catch(e){
  109. this.emit('error', e)
  110. throw e
  111. }
  112. }
  113. /**
  114. * An alternative to call that does not wait for confirmation and doesn't return a value.
  115. * @param rpcname The function to call
  116. * @param args other arguments
  117. */
  118. public async fire(rpcname: string, ...args: any[]) : Promise<void>{
  119. if(!this.socket) throw new Error("The socket is not connected! Use socket.connect() first")
  120. await this.socket.fire.apply(this.socket, [rpcname, ...args])
  121. }
  122. /**
  123. * Connects to the server and attaches available RPCs to this object
  124. */
  125. public async connect( sesame?: string ) : Promise<T.ConnectedSocket<Ifc>> {
  126. try{
  127. this.socket = await PromiseIOClient.connect(this.port, this.server, this.protocol)
  128. }catch(e){
  129. this.handlers['error'].forEach(h => h(e))
  130. throw e
  131. }
  132. Object.entries(this.handlers).forEach(([k,v])=>{
  133. v.forEach(h => this.socket.on(k, h))
  134. })
  135. Object.entries(this.hooks).forEach((kv: [string, T.AnyFunction]) => {
  136. this.socket.hook(kv[0], kv[1])
  137. })
  138. const info:T.ExtendedRpcInfo[] = await this.info(sesame)
  139. info.forEach(i => {
  140. let f: any
  141. switch (i.type) {
  142. case 'Call':
  143. f = this.callGenerator(i.uniqueName, i.argNames, sesame)
  144. break
  145. case 'Hook':
  146. f = this.frontEndHookGenerator(i.uniqueName, i.argNames, sesame)
  147. break
  148. }
  149. if(this[i.owner] == null)
  150. this[i.owner] = {}
  151. this[i.owner][i.name] = f
  152. this[i.owner][i.name].bind(this)
  153. })
  154. return <T.ConnectedSocket<Ifc>> (this as any)
  155. }
  156. /**
  157. * Get a list of available RPCs from the server
  158. */
  159. public async info(sesame?:string){
  160. if(!this.socket) throw new Error("The socket is not connected! Use socket.connect() first")
  161. return await this.socket.call('info', sesame)
  162. }
  163. /**
  164. * Utility {@link AsyncFunction} generator
  165. * @param fnName The function name
  166. * @param fnArgs A string-list of parameters
  167. */
  168. private callGenerator(fnName: string, fnArgs:string[], sesame?:string): T.AnyFunction{
  169. const headerArgs = fnArgs.join(",")
  170. const argParams = fnArgs.map(stripAfterEquals).join(",")
  171. sesame = appendComma(sesame)
  172. return eval(`async (${headerArgs}) => {
  173. return await this.call("${fnName}", ${sesame} ${argParams})
  174. }`)
  175. }
  176. /**
  177. * Utility {@link HookFunction} generator
  178. * @param fnName The function name
  179. * @param fnArgs A string-list of parameters
  180. */
  181. private frontEndHookGenerator(fnName: string, fnArgs:string[], sesame?:string): T.HookFunction{
  182. if(sesame)
  183. fnArgs.shift()
  184. let headerArgs = fnArgs.join(",")
  185. const argParams = fnArgs.map(stripAfterEquals).join(",")
  186. sesame = appendComma(sesame, true)
  187. headerArgs = fnArgs.length>0?headerArgs+",":headerArgs
  188. return eval( `
  189. async (${headerArgs} callback) => {
  190. const r = await this.call("${fnName}", ${sesame} ${argParams})
  191. try{
  192. if(r){
  193. if(r.uuid){
  194. callback['destroy'] = () => { this.socket.unhook(r.uuid) }
  195. this.socket.hook(r.uuid, callback)
  196. }
  197. return r.return
  198. }else{
  199. throw new Error("Empty response")
  200. }
  201. }catch(e){
  202. throw e
  203. }
  204. }`)
  205. }
  206. }