import axios from "axios";
/**
* Base URL for Clockify API
*/
const API_BASE_URL = "https://api.clockify.me/api/v1";
/**
* Retrieves the Clockify API key from environment variables.
* @returns {string} The API key.
* @throws {Error} If the API key is not set.
*/
export function getApiKey() {
const apiKey = process.env.CLOCKIFY_API_KEY;
if (!apiKey) {
throw new Error("CLOCKIFY_API_KEY environment variable is required");
}
return apiKey;
}
/**
* Makes an API request to the Clockify API.
* @param {string} endpoint - The API endpoint (relative to base URL).
* @param {string} [method="GET"] - HTTP method.
* @param {object|null} [body=null] - Request body for POST/PUT requests.
* @param {object} [customHeaders={}] - Optional custom headers.
* @returns {Promise<any>} The parsed JSON response.
* @throws {Error} If the request fails.
*/
export async function makeApiRequest(endpoint, method = "GET", body = null, customHeaders = {}) {
const apiKey = getApiKey();
const headers = {
"x-api-key": apiKey,
"Content-Type": "application/json",
...customHeaders,
};
const axiosConfig = {
method,
url: API_BASE_URL + endpoint,
headers,
data: body && method !== "GET" ? body : undefined,
};
try {
const response = await axios(axiosConfig);
return response.data;
} catch (error) {
console.log({error})
if (error.response) {
// Server responded with a status other than 2xx
throw new Error(`API request failed: ${error.response.status} - ${JSON.stringify(error.response.data)}`);
} else if (error.request) {
// Request was made but no response received
throw new Error(`No response received: ${error.message}`);
} else {
// Something happened in setting up the request
throw new Error(`Request setup error: ${error.message}`);
}
}
}