#Throwing an async Error outside the Context of nestjs outside the Framework

1 messages · Page 1 of 1 (latest)

graceful patrol
#
@Injectable()
export class ConnectionErrorService {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private readonly errorSource = new Subject<any>();

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  get errors$(): Observable<any> {
    return this.errorSource.asObservable();
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  notifyError(error: { message: string; status: number; rawError: any }): void {
    Logger.error("from notify error");
    this.errorSource.next(error);
  }
}
#
@Injectable({ scope: Scope.REQUEST })
export class ConnectionService {
  constructor(
    @Inject(SHOPIFY) private readonly shopify: Shopify,
    @Inject(REQUEST) private readonly request: FastifyRequest,
    private readonly sessionDrizzleRepository: SessionDrizzleRepository,
    private readonly connectionErrorService: ConnectionErrorService,
    private readonly configService: ConfigService,
  ) {}

  async getShopifyAdminGraphqlClient(): Promise<Client> {
    const session = await this.getCurrentSession();
    let currentAttempt = 1;
    const maxAttempts = 4;
    return new Client({
      url: `https://${session.shopId}/admin/api/${this.configService.getOrThrow(
        "SHOPIFY_API_VERSION",
      )}/graphql.json`,
      fetchOptions: {
        headers: {
          "X-Shopify-Access-Token": session.accessToken,
          "Content-Type": "application/json",
        },
      },
      exchanges: [
        retryExchange({
        // logic too long for discord
        }),
        errorExchange({
          onError: (error) => {
            currentAttempt++;
            if (currentAttempt === maxAttempts) {
              Logger.warn(
                `Max attempts reached ${currentAttempt} for graphql Admin API of ${session.shopId}`,
              );

              this.connectionErrorService.notifyError({
                message: error.message,
                status: error.networkError
                  ? HttpStatus.SERVICE_UNAVAILABLE
                  : 500,
                rawError: error,
              });
            }
          },
        }),
        fetchExchange,
      ],
      fetch,
    });
  }