-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathService.ts
139 lines (121 loc) · 4.44 KB
/
Service.ts
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import axios, {
AxiosError,
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
} from "axios";
import { IServiceOptions, SimilarWebError } from "./Service.types";
import { Utilities } from "./components/utilities/Utilities";
import { TotalTraffic } from "./components/totalTraffic/TotalTraffic";
import { IMeta } from "./components/Component.types";
import { SalesSolution } from "./components/salesSolution/SalesSolution";
import { DesktopOther } from "./components/desktopOther/DesktopOther";
import { DesktopKeywordAnalysis } from "./components/desktopKeywordAnalysis/DesktopKeywordAnalysis";
import { DesktopWebTrafficSources } from "./components/desktopWebTrafficSources/DesktopWebTrafficSources";
import { MobileWebTrafficSources } from "./components/mobileWebTrafficSources/MobileWebTrafficSources";
export default class Service {
protected static PRODUCTION_SERVER = "https://api.similarweb.com/";
public static DEFAULT_TIMEOUT = 10000;
protected client: AxiosInstance;
protected options: IServiceOptions = {
apiKey: "",
onInvalidCredentials: () => {},
};
public desktopKeywordAnalysis: DesktopKeywordAnalysis;
public desktopOther: DesktopOther;
public desktopWebTrafficSources: DesktopWebTrafficSources;
public mobileWebTrafficSources: MobileWebTrafficSources;
public salesSolution: SalesSolution;
public totalTraffic: TotalTraffic;
public utilities: Utilities;
public static formatDate(date: Date, granularity: "date" | "month" = "date") {
const formattedDate = date.toISOString().split("T").shift();
if (granularity === "date") {
return formattedDate;
}
const [year, month] = formattedDate.split("-");
return `${year}-${month}`;
}
public static getServiceUrl() {
return Service.PRODUCTION_SERVER;
}
constructor(options: Partial<IServiceOptions>) {
this.setOptions(options);
}
protected setEnvironment() {
this.client = axios.create({
baseURL: Service.getServiceUrl(),
timeout: Service.DEFAULT_TIMEOUT,
});
// Bind to incoming requests
this.client.interceptors.request.use(this.onRequest.bind(this));
// Bind to responses
this.client.interceptors.response.use(
this.onResponseSuccess.bind(this),
this.onResponseError.bind(this)
);
this.desktopKeywordAnalysis = new DesktopKeywordAnalysis(this.client);
this.desktopOther = new DesktopOther(this.client);
this.desktopWebTrafficSources = new DesktopWebTrafficSources(this.client);
this.mobileWebTrafficSources = new MobileWebTrafficSources(this.client);
this.salesSolution = new SalesSolution(this.client);
this.totalTraffic = new TotalTraffic(this.client);
this.utilities = new Utilities(this.client);
return this;
}
setOptions(options: Partial<IServiceOptions>) {
this.options = { ...this.options, ...options };
this.setEnvironment();
return this;
}
/**
* Modifies the original request adding authorization if required.
*/
protected onRequest(
originalRequest: AxiosRequestConfig
): Promise<AxiosRequestConfig> {
// Return a promise as some requests may need to try auth
return new Promise((resolve, reject) => {
const { apiKey } = this.options;
originalRequest.params = originalRequest.params || {};
originalRequest.params.api_key = apiKey;
resolve(originalRequest);
});
}
/**
* Provides success response handling
*/
protected onResponseSuccess(
response: AxiosResponse
): Promise<AxiosResponse<IMeta<any>>> {
// Return a promise as some requests may need to retry auth
return new Promise((resolve, reject) => {
if (response.data.meta?.error_code) {
return reject(this.getSimilarWebError(response.data.meta));
}
resolve(response);
});
}
/**
* Provides failure response handling
*/
protected onResponseError(error: AxiosError<IMeta<any>>) {
// Return a promise as some requests may need to retry auth
return new Promise((resolve, reject) => {
if (error.response && error.response.status === 401) {
this.options.onInvalidCredentials();
}
if (error.response?.data?.meta?.error_code) {
return reject(this.getSimilarWebError(error.response.data.meta));
}
reject(error);
});
}
protected getSimilarWebError(meta: IMeta<any>["meta"]) {
const { status, error_code, error_message } = meta;
return new SimilarWebError(
`${status} ${error_code} - ${error_message}`,
error_code
);
}
}