import { Injectable } from "@angular/core"; import { Apollo, gql } from "apollo-angular"; import { catchError, of } from "rxjs"; import { ApolloQueryResult } from "./models"; @Injectable({ providedIn: 'root' }) export class GraphQLComponent { constructor(public apollo: Apollo) {} // READ read(query: string, variables: any, fetchPolicy?: any, newVersion:boolean=false) { const request = this.apollo.query({ query: gql`${query}`, variables: variables, fetchPolicy: fetchPolicy }); return !newVersion ? request : request.pipe(catchError((err:any)=> this.getCatchError(err) )); } // UPDATE update(query: string, variables:any, newVersion:boolean=false){ const request = this.apollo .mutate({ mutation: gql`${query}`, variables }); return !newVersion ? request : request.pipe(catchError((err:any)=> this.getCatchError(err) )); } // WATCH watchQuery(query: string, variables: any) { return this.apollo .watchQuery({ query: gql`${query}`, variables: variables }); } resetCacheApollo() { this.apollo.client.resetStore(); } // DEPRECAR METODOS - create & delete create(query: any, variables?: any, newVersion:boolean=false) { const request = this.apollo .mutate({ mutation: gql`${query}`, variables }); return !newVersion ? request : request.pipe(catchError((err:any)=> this.getCatchError(err) )); } delete(query: string, variables:any, newVersion:boolean=false){ const request = this.apollo .mutate({ mutation: gql`${query}`, variables }); return !newVersion ? request : request.pipe(catchError((err:any)=> this.getCatchError(err) )); } private getCatchError(err:any){ return of( this.standardizeError(err) ) } private standardizeError(err: any): ApolloQueryResult { const standardizedError: ApolloQueryResult = { data: undefined, loading: false, networkStatus: 8, error: undefined }; if (err.networkError) { standardizedError.error = { errorMessage: err.networkError.message, stacktrace: [err.networkError.message], }; } if (err.graphQLErrors && err.graphQLErrors.length > 0) { const firstGraphQLError = err.graphQLErrors[0]; standardizedError.error = { errorMessage: firstGraphQLError.message, code: firstGraphQLError.extensions?.code, locations: firstGraphQLError.locations, stacktrace: firstGraphQLError.extensions?.stacktrace, }; } if (!err.networkError && (!err.graphQLErrors || err.graphQLErrors.length === 0)) { standardizedError.error = { errorMessage: 'Error desconocido.' // Mensaje de error genérico }; } return standardizedError; } }