All files / src/services detector.ts

92.86% Statements 13/14
50% Branches 1/2
100% Functions 4/4
100% Lines 13/13

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 664x 4x 4x             4x         4x 1x 1x                       2x   2x                   2x           1x                   1x           1x      
import { stringify } from "query-string";
import { ExtendedError } from "../error";
import { HttpAPI } from "../http";
import { AnyResponse } from "./shared.types";
 
/**
 * Ошибка, которую выбрасывает персональное API в случае
 * неправильного кода ответа от QIWI
 */
export class DetectorError extends ExtendedError {}
 
/**
 * API получения ID провайдера QIWI по Номеру Телефона/Карте
 */
export class Detector extends HttpAPI {
  protected readonly API_URL = "https://qiwi.com";
  protected readonly API_HEADERS = {
    "Content-Type": "application/x-www-form-urlencoded",
    Accept: "application/json"
  };
 
  /**
   * Вытаскивает ID провайдера из объекта ответа
   *
   * @param {*} response
   * @return {number} ID провайдера
   */
  private _extractProvider(response: AnyResponse): number {
    Iif (response.code.value !== "0") throw new DetectorError(response.message);
 
    return Number.parseInt(response.message);
  }
 
  /**
   * Возвращает ID провайдера QIWI по номеру телефона.
   * Используется для пополнения на счёта мобильного
   *
   * @param {string} phone
   */
  async getPhoneProvider(phone: string): Promise<number> {
    const response = await this.post<any>(
      "mobile/detect.action",
      {},
      stringify({ phone })
    );
 
    return this._extractProvider(response);
  }
 
  /**
   * Возвращает ID провайдера QIWI по номеру карты.
   * Используется для переводов на карту
   *
   * @param {string} cardNumber
   */
  async getCardProvider(cardNumber: string): Promise<number> {
    const response = await this.post<any>(
      "card/detect.action",
      {},
      stringify({ cardNumber })
    );
 
    return this._extractProvider(response);
  }
}