// Figma API service
const axios = require('axios');
const utils = require('./utils');
/**
* FigmaService - Handles all Figma API requests
*/
class FigmaService {
constructor() {
this.baseUrl = 'https://api.figma.com/v1';
this.headers = {
'Content-Type': 'application/json'
};
}
/**
* Set the Figma API token
* @param {string} token - Figma API token
*/
setToken(token) {
if (!token) {
throw new Error('Figma API token is required');
}
this.headers['X-Figma-Token'] = token;
}
/**
* Validate that the token is set
*/
validateToken() {
if (!this.headers['X-Figma-Token']) {
throw new Error('Figma API token is not set. Call setToken() first.');
}
}
/**
* Get file data by key
* @param {string} fileKey - Figma file key
* @returns {Promise<object>} File data
*/
async getFile(fileKey) {
this.validateToken();
try {
utils.log(`Fetching Figma file: ${fileKey}`, 'debug');
const response = await axios.get(`${this.baseUrl}/files/${fileKey}`, { headers: this.headers });
utils.log(`Successfully fetched Figma file: ${fileKey}`, 'debug');
return response.data;
} catch (error) {
const errorMessage = error.response?.data?.message || error.message;
utils.log(`Error fetching Figma file: ${errorMessage}`, 'error');
throw new Error(`Failed to fetch Figma file: ${errorMessage}`);
}
}
/**
* Fetch Figma data from URL
* @param {string} url - Figma file URL or key
* @returns {Promise<object>} Result containing file data and key
*/
async fetchFigmaFromUrl(url) {
try {
// Extract file key from URL
const fileKey = utils.extractFigmaKey(url);
utils.log(`Extracted Figma file key: ${fileKey}`, 'debug');
// Get file data
const data = await this.getFile(fileKey);
return {
data,
fileKey,
source: url
};
} catch (error) {
utils.log(`Error in fetchFigmaFromUrl: ${error.message}`, 'error');
throw error;
}
}
}
// Create and export a singleton instance
const figmaService = new FigmaService();
// Configure with environment token if available
if (process.env.FIGMA_TOKEN) {
try {
figmaService.setToken(process.env.FIGMA_TOKEN);
} catch (error) {
utils.log(`Error setting Figma token: ${error.message}`, 'error');
}
}
module.exports = figmaService;