vchikalkin 8cb283d4ba Refactor GraphQL client usage in services to improve consistency
- Replaced direct calls to `getClientWithToken` with a new method `getGraphQLClient` across multiple services, ensuring a unified approach to obtaining the GraphQL client.
- Updated the `BaseService` to manage the GraphQL client instance, enhancing performance by reusing the client when available.
2025-09-30 19:02:11 +03:00

76 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* eslint-disable canonical/id-match */
import { getClientWithToken } from '../apollo/client';
import { ERRORS as SHARED_ERRORS } from '../constants/errors';
import * as GQL from '../types';
import { type ApolloClient, type NormalizedCacheObject } from '@apollo/client';
import { isCustomerBanned } from '@repo/utils/customer';
export const ERRORS = {
MISSING_TELEGRAM_ID: 'Не указан Telegram ID',
NOT_FOUND_CUSTOMER: 'Пользователь не найден',
} as const;
type UserProfile = {
telegramId: number;
};
export class BaseService {
protected _user: UserProfile;
protected graphQL: ApolloClient<NormalizedCacheObject> | null;
constructor(user: UserProfile) {
if (!user?.telegramId) {
throw new Error(ERRORS.MISSING_TELEGRAM_ID);
}
this._user = user;
this.graphQL = null;
}
protected async _getUser() {
const { query } = await this.getGraphQLClient();
const result = await query({
query: GQL.GetCustomerDocument,
variables: this._user,
});
const customer = result.data.customers.at(0);
if (!customer) throw new Error(ERRORS.NOT_FOUND_CUSTOMER);
if (isCustomerBanned(customer)) {
throw new Error(SHARED_ERRORS.NO_PERMISSION);
}
return { customer };
}
protected async checkIsBanned() {
const { query } = await this.getGraphQLClient();
const result = await query({
query: GQL.GetCustomerDocument,
variables: this._user,
});
const customer = result.data.customers.at(0);
if (!customer) throw new Error(ERRORS.NOT_FOUND_CUSTOMER);
if (customer && isCustomerBanned(customer)) {
throw new Error(SHARED_ERRORS.NO_PERMISSION);
}
return { customer };
}
protected async getGraphQLClient() {
if (!this.graphQL) this.graphQL = await getClientWithToken();
return this.graphQL;
}
}