|
| 1 | +import { ACTION_ID_LENGTH, MESSAGE_ID } from './constants'; |
| 2 | +import type { IExternalComponentRoomInfo, IExternalComponentUserInfo } from './definition'; |
| 3 | +import { AppsEngineUIMethods } from './definition/AppsEngineUIMethods'; |
| 4 | +import { randomString } from './utils'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Represents the SDK provided to the external component. |
| 8 | + */ |
| 9 | +export class AppsEngineUIClient { |
| 10 | + private listener: (this: Window, ev: MessageEvent) => any; |
| 11 | + |
| 12 | + private callbacks: Map<string, (response: any) => any>; |
| 13 | + |
| 14 | + constructor() { |
| 15 | + this.listener = () => console.log('init'); |
| 16 | + this.callbacks = new Map(); |
| 17 | + } |
| 18 | + |
| 19 | + /** |
| 20 | + * Get the current user's information. |
| 21 | + * |
| 22 | + * @return the information of the current user. |
| 23 | + */ |
| 24 | + public getUserInfo(): Promise<IExternalComponentUserInfo> { |
| 25 | + return this.call(AppsEngineUIMethods.GET_USER_INFO); |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Get the current room's information. |
| 30 | + * |
| 31 | + * @return the information of the current room. |
| 32 | + */ |
| 33 | + public getRoomInfo(): Promise<IExternalComponentRoomInfo> { |
| 34 | + return this.call(AppsEngineUIMethods.GET_ROOM_INFO); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Initialize the app SDK for communicating with Rocket.Chat |
| 39 | + */ |
| 40 | + public init(): void { |
| 41 | + this.listener = ({ data }) => { |
| 42 | + if (!data?.hasOwnProperty(MESSAGE_ID)) { |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + const { |
| 47 | + [MESSAGE_ID]: { id, payload }, |
| 48 | + } = data; |
| 49 | + |
| 50 | + if (this.callbacks.has(id)) { |
| 51 | + const resolve = this.callbacks.get(id); |
| 52 | + |
| 53 | + if (typeof resolve === 'function') { |
| 54 | + resolve(payload); |
| 55 | + } |
| 56 | + this.callbacks.delete(id); |
| 57 | + } |
| 58 | + }; |
| 59 | + window.addEventListener('message', this.listener); |
| 60 | + } |
| 61 | + |
| 62 | + private call(action: string, payload?: any): Promise<any> { |
| 63 | + return new Promise((resolve) => { |
| 64 | + const id = randomString(ACTION_ID_LENGTH); |
| 65 | + |
| 66 | + window.parent.postMessage({ [MESSAGE_ID]: { action, payload, id } }, '*'); |
| 67 | + this.callbacks.set(id, resolve); |
| 68 | + }); |
| 69 | + } |
| 70 | +} |
0 commit comments