@lexriver/yandex-pay
Version:
A TypeScript client for Yandex Pay API to integrate payment processing in your Node.js applications
87 lines (86 loc) • 2.44 kB
JavaScript
/**
* Base service class for making API requests
*/
export class BaseService {
/**
* Creates a new BaseService instance
*
* @param baseUrl Base URL for API requests
* @param apiKey API key for authentication
*/
constructor(baseUrl, apiKey) {
this.baseUrl = baseUrl;
this.apiKey = apiKey;
}
/**
* Makes a GET request to the API
*
* @param path API path
* @param params Query parameters
* @returns Response data
*/
async get(path, params) {
const url = new URL(`${this.baseUrl}${path}`);
if (params) {
Object.entries(params).forEach(([key, value]) => {
url.searchParams.append(key, value);
});
}
const response = await fetch(url.toString(), {
method: 'GET',
headers: this.getHeaders(),
});
return this.handleResponse(response);
}
/**
* Makes a POST request to the API
*
* @param path API path
* @param data Request body
* @returns Response data
*/
async post(path, data) {
const url = new URL(`${this.baseUrl}${path}`);
const response = await fetch(url.toString(), {
method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify(data),
});
return this.handleResponse(response);
}
/**
* Gets the headers for API requests
*/
getHeaders() {
const requestId = this.generateRequestId();
const result = {
'Content-Type': 'application/json',
'Authorization': `Api-Key ${this.apiKey}`,
'X-Request-Id': requestId,
'X-Request-Timeout': '20000',
'X-Request-Attempt': '0',
};
// console.log('header=', result);
return result;
}
/**
* Generates a request ID
*/
generateRequestId() {
return `req-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
}
/**
* Handles the API response
*
* @param response Fetch Response
* @returns Response data
*/
async handleResponse(response) {
if (!response.ok) {
const errorData = await response.json();
throw new Error(`API Error: ${response.status} - ${JSON.stringify(errorData)}`);
}
const data = await response.json();
return data.data;
}
}