---
# System prepended metadata

title: Classic http service
tags: [Typescript]

---

# Classic http service 

###### tags: `Typescript`

> Пример HttpService для фронтенда на базе Axios. Из-за отсвутсвия Dependecy injection приходится делать singltone сервисы.

```typescript=
import Axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

export class HttpServiceClass {
  private readonly _instance: AxiosInstance = Axios.create({
    withCredentials: true,
  });

  public get axiosRef(): AxiosInstance {
    return this._instance;
  }

  public request<T = any>(config: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return this._instance.request<T>(config);
  }

  public get<T = any>(
    url: string,
    config?: AxiosRequestConfig,
  ): Promise<AxiosResponse<T>> {
    return this._instance.get<T>(url, config);
  }

  public delete<T = any>(
    url: string,
    config?: AxiosRequestConfig,
  ): Promise<AxiosResponse<T>> {
    return this._instance.delete(url, config);
  }

  public head<T = any>(
    url: string,
    config?: AxiosRequestConfig,
  ): Promise<AxiosResponse<T>> {
    return this._instance.head(url, config);
  }

  public post<T = any, D = any>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig,
  ): Promise<AxiosResponse<T>> {
    return this._instance.post(url, data, config);
  }

  public put<T = any, D = any>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig,
  ): Promise<AxiosResponse<T>> {
    return this._instance.put(url, data, config);
  }

  public patch<T = any, D = any>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig,
  ): Promise<AxiosResponse<T>> {
    return this._instance.patch(url, data, config);
  }

  public extractResponseData<T = any>(res: AxiosResponse): T {
    return res.data;
  }
}

export const HttpService = new HttpServiceClass();
```

Пример использования

```typescript=
import { HttpService } from "../http.service";
import { IPayment } from '../types';


class BillingApiServiceClass {
  public get http() {
    return HttpService;
  }

  private _buildUrl(path: string): string {
    return `${process.env.REACT_APP_CORE_API_URL}/api/v1/payments/${path}`;
  }

  public async markAsPaid(paymentId: string): Promise<IPayment> {
    const url = this._buildUrl(paymentId);

    return this.http.post(url).then(this.http.extractResponseData);
  }
}

export const BillingApiService = new BillingApiServiceClass();
```
