client.js•1.61 kB
import { config } from '../config.js';
import { logger } from '../utils/logger.js';
export class TwentyAPIClient {
constructor() {
this.apiKey = config.apiKey;
this.baseUrl = config.baseUrl;
}
async makeRequest(endpoint, method = "GET", data = null, params = {}) {
const url = new URL(`${this.baseUrl}${endpoint}`);
if (method === "GET" && params) {
Object.keys(params).forEach(key => {
if (params[key] !== undefined && params[key] !== null) {
url.searchParams.append(key, params[key]);
}
});
}
const options = {
method,
headers: {
"Authorization": `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
},
};
if (data && (method === "POST" || method === "PUT" || method === "PATCH")) {
options.body = JSON.stringify(data);
}
logger.debug(`Making request to: ${url.toString()}`);
logger.debug(`Method: ${method}`);
if (data) logger.debug(`Data:`, data);
try {
const response = await fetch(url.toString(), options);
logger.debug(`Response status: ${response.status}`);
if (!response.ok) {
const errorText = await response.text();
logger.debug(`Error response: ${errorText}`);
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
const result = await response.json();
logger.debug(`Success response received`);
return result;
} catch (error) {
logger.error(`Request error:`, error.message);
throw new Error(`API request failed: ${error.message}`);
}
}
}