(config: RequestConfig)
| 35 | private readonly REQUEST_CACHE_TIME = 100; |
| 36 | |
| 37 | public async subscribe<T>(config: RequestConfig): Promise<T | undefined> { |
| 38 | if (!config.url) throw new Error("ApiService: RequestConfig: 'url' is empty!"); |
| 39 | |
| 40 | config = _.cloneDeep(config); |
| 41 | // filter and clean up expired cache tables |
| 42 | this.responseMap.forEach((value, key) => { |
| 43 | if (value.timestamp + this.RESPONSE_CACHE_TIME < Date.now()) { |
| 44 | this.responseMap.delete(key); |
| 45 | } |
| 46 | }); |
| 47 | |
| 48 | if (config.url?.startsWith("/")) { |
| 49 | config.url = "." + config.url; |
| 50 | } |
| 51 | |
| 52 | if (config.forceRequest === true) { |
| 53 | config.params = config?.params || {}; |
| 54 | config.params._force = Date.now(); |
| 55 | return await this.sendRequest<T>(config); |
| 56 | } |
| 57 | |
| 58 | const reqId = encodeURIComponent( |
| 59 | [ |
| 60 | String(config.method), |
| 61 | String(config.url), |
| 62 | JSON.stringify(config.data ?? {}), |
| 63 | JSON.stringify(config.params ?? {}) |
| 64 | ].join("") |
| 65 | ); |
| 66 | |
| 67 | return new Promise((resolve, reject) => { |
| 68 | this.event.once(reqId, (data: any) => { |
| 69 | if (data instanceof Error) { |
| 70 | if (config.errorAlert === true) { |
| 71 | reportErrorMsg(data.message); |
| 72 | } |
| 73 | reject(data); |
| 74 | } else { |
| 75 | data = _.cloneDeep(data); |
| 76 | resolve(data); |
| 77 | } |
| 78 | }); |
| 79 | |
| 80 | if (this.responseMap.has(reqId) && !config.forceRequest) { |
| 81 | const cache = this.responseMap.get(reqId) as ResponseDataRecord; |
| 82 | if (cache.timestamp + this.RESPONSE_CACHE_TIME > Date.now()) { |
| 83 | return this.event.emit(reqId, cache.data); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | if (this.event.listenerCount(reqId) <= 1 || config.forceRequest === true) { |
| 88 | this.sendRequest(config, reqId); |
| 89 | } |
| 90 | }); |
| 91 | } |
| 92 | |
| 93 | private async sendRequest<T>(config: RequestConfig, reqId?: string) { |
| 94 | try { |
nothing calls this directly
no test coverage detected