|
| 1 | +import { HttpClient } from '@angular/common/http'; |
| 2 | +import { inject } from '@angular/core'; |
| 3 | +import { Router } from '@angular/router'; |
| 4 | +import { CURRENT_WORKSPACE_PATH } from '@angular-cli-gui/shared/data'; |
| 5 | +import { ConnectWorkspaceService } from '@angular-cli-gui/workspace-manager'; |
| 6 | +import { catchError, map, Observable, of, retry, Subject, tap } from 'rxjs'; |
| 7 | + |
| 8 | +import { CoreService } from '../core/core.service'; |
| 9 | + |
| 10 | +export const currentWorkspaceGuard = (): Observable<boolean> => { |
| 11 | + const router = inject(Router); |
| 12 | + const http = inject(HttpClient); |
| 13 | + const connectWorkspaceService = inject(ConnectWorkspaceService); |
| 14 | + const core = inject(CoreService); |
| 15 | + const retrySubject = new Subject<void>(); |
| 16 | + const projectNames$ = http.get<string[]>('/api/workspace'); |
| 17 | + const currentWorkspacePath = sessionStorage.getItem(CURRENT_WORKSPACE_PATH); |
| 18 | + |
| 19 | + return projectNames$.pipe( |
| 20 | + // Save projects to state |
| 21 | + tap((projectNames) => { |
| 22 | + core.update({ |
| 23 | + projectNames, |
| 24 | + currentProjectName: projectNames?.[0], |
| 25 | + }); |
| 26 | + }), |
| 27 | + // Map to true to allow navigation |
| 28 | + map(() => true), |
| 29 | + catchError(() => { |
| 30 | + if (!currentWorkspacePath) { |
| 31 | + router.navigate(['workspace-manager', 'connect-workspace']); |
| 32 | + return of(false); |
| 33 | + } |
| 34 | + |
| 35 | + // if path saved in local storage is invalid somehow (maybe deleted workspace) |
| 36 | + // remove it from local storage so on 2nd retry cycle user will be navigated to workspace connection screen |
| 37 | + sessionStorage.removeItem(CURRENT_WORKSPACE_PATH); |
| 38 | + |
| 39 | + // Connect to workspace using local storage path and retry to get projectNames |
| 40 | + return connectWorkspaceService |
| 41 | + .connectWorkspace(currentWorkspacePath) |
| 42 | + .pipe( |
| 43 | + map(() => { |
| 44 | + retrySubject.next(); |
| 45 | + return false; |
| 46 | + }) |
| 47 | + ); |
| 48 | + }), |
| 49 | + retry({ delay: () => retrySubject }) |
| 50 | + ); |
| 51 | +}; |
0 commit comments