github.com/argoproj/argo-cd@v1.8.7/ui/src/app/shared/services/requests.ts (about) 1 import * as path from 'path'; 2 import * as superagent from 'superagent'; 3 const superagentPromise = require('superagent-promise'); 4 import {BehaviorSubject, Observable, Observer} from 'rxjs'; 5 6 type Callback = (data: any) => void; 7 8 declare class EventSource { 9 public onopen: Callback; 10 public onmessage: Callback; 11 public onerror: Callback; 12 public readyState: number; 13 constructor(url: string); 14 public close(): void; 15 } 16 17 enum ReadyState { 18 CONNECTING = 0, 19 OPEN = 1, 20 CLOSED = 2, 21 DONE = 4 22 } 23 24 const agent: superagent.SuperAgentStatic = superagentPromise(superagent, global.Promise); 25 26 let baseHRef = '/'; 27 28 const onError = new BehaviorSubject<superagent.ResponseError>(null); 29 30 function toAbsURL(val: string): string { 31 return path.join(baseHRef, val); 32 } 33 34 function apiRoot(): string { 35 return toAbsURL('/api/v1'); 36 } 37 38 function initHandlers(req: superagent.Request) { 39 req.on('error', err => onError.next(err)); 40 return req; 41 } 42 43 export default { 44 setBaseHRef(val: string) { 45 baseHRef = val; 46 }, 47 agent, 48 toAbsURL, 49 onError: onError.asObservable().filter(err => err != null), 50 get(url: string) { 51 return initHandlers(agent.get(`${apiRoot()}${url}`)); 52 }, 53 54 post(url: string) { 55 return initHandlers(agent.post(`${apiRoot()}${url}`)); 56 }, 57 58 put(url: string) { 59 return initHandlers(agent.put(`${apiRoot()}${url}`)); 60 }, 61 62 patch(url: string) { 63 return initHandlers(agent.patch(`${apiRoot()}${url}`)); 64 }, 65 66 delete(url: string) { 67 return initHandlers(agent.del(`${apiRoot()}${url}`)); 68 }, 69 70 loadEventSource(url: string): Observable<string> { 71 return Observable.create((observer: Observer<any>) => { 72 let eventSource = new EventSource(`${apiRoot()}${url}`); 73 eventSource.onmessage = msg => observer.next(msg.data); 74 eventSource.onerror = e => () => { 75 observer.error(e); 76 onError.next(e); 77 }; 78 79 // EventSource does not provide easy way to get notification when connection closed. 80 // check readyState periodically instead. 81 const interval = setInterval(() => { 82 if (eventSource && eventSource.readyState === ReadyState.CLOSED) { 83 observer.complete(); 84 } 85 }, 500); 86 return () => { 87 clearInterval(interval); 88 eventSource.close(); 89 eventSource = null; 90 }; 91 }); 92 } 93 };