Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | 1x 23x 23x 23x 23x 23x 23x 1x 3x 3x 2x 2x 1x 2x 2x 2x 1x 1x 2x 1x 3x 3x 2x 2x 3x 3x 3x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 2x 1x 4x 1x 1x 1x 7x 7x 7x 3x 3x 3x 2x 2x 4x 2x 2x | import { HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { inject, Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { ApolloLink, ApolloQueryResult, FetchResult, Operation, ServerError, ServerParseError, split, UriFunction, } from '@apollo/client/core'; import { ErrorResponse, onError } from '@apollo/client/link/error'; import { getMainDefinition } from '@apollo/client/utilities'; import { HTTP_STATUS, WEB_CLIENT_APP_ENV } from '@app/client-util'; import { Store } from '@ngrx/store'; import { MutationResult } from 'apollo-angular'; import { HttpLink, HttpLinkHandler } from 'apollo-angular/http'; import createUploadLink from 'apollo-upload-client/createUploadLink.mjs'; import memo from 'memo-decorator'; import { MonoTypeOperatorFunction, Observable, of } from 'rxjs'; import { catchError, finalize, map, tap, timeout } from 'rxjs/operators'; import { httpProgressAction } from '../../http-progress.actions'; import { IHttpProgressState } from '../../http-progress.interface'; import { AppToasterService } from '../toaster/toaster.service'; export type TGqlClient = 'graphql'; /** * Handlers to work with http requests. */ @Injectable({ providedIn: 'root', }) export class AppHttpHandlersService { private readonly store = inject(Store<IHttpProgressState>); private readonly toaster = inject(AppToasterService); private readonly httpLink = inject(HttpLink); private readonly router = inject(Router); private readonly env = inject(WEB_CLIENT_APP_ENV); public readonly defaultHttpTimeout = 10000; /** * Gets gql http headers. * @param userToken user token * @returns the gql headers observable */ public getGraphQLHttpHeaders(userToken: string) { return new HttpHeaders({ Authorization: `Token ${userToken}`, }); } /** * Returns API base url concatenated with provided endpoint path. * Adds preceding slash before endpoint path if it is missing. * @param path endpoint path * @returns an endpoint url */ @memo() public getEndpoint(path: string): string { const endpoint = /^\/.*$/.test(path) ? path : `/${path}`; return `${this.env.api}${endpoint}`; } /** * Pipes an http response. * Attaches settings: * - timeout * - error handler * - progress indicator * @param observable input observable * @returns a piped observable */ public pipeHttpResponse<T>(observable: Observable<T>) { this.store.dispatch(httpProgressAction.start({ payload: { mainView: true } })); return observable.pipe( timeout(this.defaultHttpTimeout), this.tapError<T>(), catchError(err => this.handleError(err)), finalize(() => { this.store.dispatch(httpProgressAction.stop({ payload: { mainView: true } })); }), ); } /** * Pipes a gql response. * Attaches settings: * - timeout * - error handler * - progress indicator * @param observable input observable * @returns a piped observable */ public pipeGqlResponse<T>(observable: Observable<ApolloQueryResult<T> | FetchResult<T> | MutationResult<T>>) { this.store.dispatch(httpProgressAction.start({ payload: { mainView: true } })); return observable.pipe( timeout(this.defaultHttpTimeout), this.tapError(), map(result => ('data' in result ? result.data : result)), catchError(err => this.handleGqlError(err)), finalize(() => { this.store.dispatch(httpProgressAction.stop({ payload: { mainView: true } })); }), ); } /** * Gets the gql network link. * @param hander http link handler * @param uri universal resource indentifier * @param userToken user token * @returns gql link */ private createGqlNetworkLink(splitTest: (op: Operation) => boolean, hander: HttpLinkHandler, uri: string, userToken: string) { return split( splitTest, hander, createUploadLink({ uri, headers: { Authorization: `Token ${userToken}` }, }) as unknown as ApolloLink, ); } /** * Gql link split test function. */ public gqlLinkSplitTest() { const uploadMutations = ['UploadFile']; return (operation: Operation) => { const { name } = getMainDefinition(operation.query); return typeof name === 'undefined' || !uploadMutations.includes(name.value); }; } /** * Gets the gql error link handler. * @returns apollo error link handler */ public gqlErrorLinkHandler(error: ErrorResponse) { const { graphQLErrors, networkError } = error; let errorMessage = ''; graphQLErrors?.map(({ message, extensions }) => { console.error('Apollo linkHandler [GraphQL error]: ', message); const code = extensions?.['code'] as string; const result = `[GraphQL error ${code}]: ${message}`; errorMessage += result; }); if (typeof networkError !== 'undefined') { console.error('Apollo linkHandler [Network error]: ', networkError); Iif (networkError instanceof HttpErrorResponse) { errorMessage += (networkError.error as { detail: string }).detail; } else { const code = (networkError as (ServerParseError & ServerError) | null)?.statusCode; const result = `[Network error ${code}]: ${networkError?.message}`; errorMessage += result; } } errorMessage = errorMessage.length === 0 ? 'Graphql request error' : errorMessage; this.toaster.showToaster(errorMessage, 'error'); } /** * Creates the gql link with an error handler. * @param userToken user token * @param name the client name * @returns apollo link observable */ public createGqlLink(userToken: string, name: TGqlClient = 'graphql'): ApolloLink { const uri = this.getEndpoint(name); const uriFn = this.gqlUriFunction(uri); const httpLinkHandler = this.httpLink.create({ uri: uriFn, }); const linkHandler: ApolloLink = onError((error: ErrorResponse) => this.gqlErrorLinkHandler(error)); const splitTest = this.gqlLinkSplitTest(); const networkLink = this.createGqlNetworkLink(splitTest, httpLinkHandler, uri, userToken); return linkHandler.concat(networkLink); } /** * Gql URI function. * @param uri graphql endpoint */ public gqlUriFunction(uri: string): UriFunction { return (operation: Operation) => { return `${uri}?operation=${operation.operationName}`; }; } /** * Check error status, and reset token if status is 401. * @param status error status */ public checkErrorStatusAndRedirect(status: HTTP_STATUS): void { if (status === HTTP_STATUS.UNAUTHORIZED) { const message = 'Something went wrong during authorization or you are not authorized to see this content.'; this.toaster.showToaster(message, 'error'); void this.router.navigate([{ outlets: { primary: [''] } }]); } } /** * Gets an error message from an http error response. * @param error http error response * @returns an error message */ public getErrorMessage(error: HttpErrorResponse): string { const message: string | undefined = error.message ? error.message : error.error; const result: string = typeof message !== 'undefined' ? message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; return result; } /** * Handles error. * @param error error object * @returns an empty observable */ public handleError(error: HttpErrorResponse): Observable<never> { const message = this.getErrorMessage(error); this.toaster.showToaster(message, 'error'); return of(); } /** * Handles a graphQL error. * @param error error message * @returns an empty observable */ public handleGqlError(error: string): Observable<never> { this.toaster.showToaster(error, 'error'); return of(); } /** * Taps errors. * @returns a monotype operator function */ public tapError<T>(): MonoTypeOperatorFunction<T> { return tap({ next: (): void => void 0, error: (error: HttpErrorResponse) => { this.checkErrorStatusAndRedirect(error.status); }, }); } } |