UNPKG

imagic-sdk

Version:

Official Node.js SDK for Imagic image optimization API

169 lines 6.08 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ImagicClient = void 0; const node_fetch_1 = __importDefault(require("node-fetch")); const form_data_1 = __importDefault(require("form-data")); const types_1 = require("./types"); const utils_1 = require("./utils"); /** * Official Imagic Node.js SDK Client */ class ImagicClient { constructor(config) { (0, utils_1.validateApiKey)(config.apiKey); this.apiKey = config.apiKey; this.baseUrl = config.baseUrl || "http://localhost:3000"; this.timeout = config.timeout || 30000; // 30 seconds default // Validate base URL (0, utils_1.validateUrl)(this.baseUrl); } /** * Upload an image file to Imagic * @param input - File path (string) or Buffer * @param options - Upload options * @returns Promise<ApiResponse> */ async upload(input, options = {}) { try { let buffer; let filename; let contentType; // Handle different input types if (typeof input === "string") { // File path buffer = await (0, utils_1.readFileFromPath)(input); filename = options.filename || (0, utils_1.extractFilename)(input); contentType = options.contentType || (0, utils_1.detectMimeTypeFromExtension)(filename); } else { // Buffer buffer = input; filename = options.filename || "image.jpg"; contentType = options.contentType || (0, utils_1.detectMimeTypeFromExtension)(filename); } // Validate file size (0, utils_1.validateFileSize)(buffer.length); // Validate content type if (!(0, utils_1.isValidMimeType)(contentType)) { throw new types_1.ValidationError(`Unsupported file type: ${contentType}`); } // Create form data const formData = new form_data_1.default(); formData.append("image", buffer, { filename, contentType, }); formData.append("api_key", this.apiKey); // Make request const response = await this.makeRequest("/api/v1/upload", { method: "POST", body: formData, headers: formData.getHeaders(), }); const data = (await response.json()); if (!response.ok) { this.handleErrorResponse(response.status, data); } return data; } catch (error) { if (error instanceof types_1.ImagicError) { throw error; } throw new types_1.ImagicError(`Upload failed: ${error instanceof Error ? error.message : "Unknown error"}`, 500, "upload_error"); } } /** * Upload multiple images * @param inputs - Array of file paths or buffers * @param options - Upload options * @returns Promise<ApiResponse[]> */ async uploadMultiple(inputs, options = {}) { const uploadPromises = inputs.map((input, index) => { const indexedOptions = { ...options, filename: options.filename ? `${index}_${options.filename}` : undefined, }; return this.upload(input, indexedOptions); }); return Promise.all(uploadPromises); } /** * Get API information * @returns Promise<ApiInfo> */ async getApiInfo() { try { const response = await this.makeRequest("/api/v1"); if (!response.ok) { throw new types_1.NetworkError(`Failed to get API info: ${response.status} ${response.statusText}`); } return (await response.json()); } catch (error) { if (error instanceof types_1.ImagicError) { throw error; } throw new types_1.NetworkError(`Failed to get API info: ${error instanceof Error ? error.message : "Unknown error"}`); } } /** * Test the API connection and authentication * @returns Promise<boolean> */ async testConnection() { try { await this.getApiInfo(); return true; } catch { return false; } } /** * Make HTTP request to the API */ async makeRequest(endpoint, options = {}) { const url = new URL(endpoint, this.baseUrl).toString(); const requestOptions = { ...options, timeout: this.timeout, }; try { const response = await (0, node_fetch_1.default)(url, requestOptions); return response; } catch (error) { throw new types_1.NetworkError(`Network request failed: ${error instanceof Error ? error.message : "Unknown error"}`); } } /** * Handle error responses from the API */ handleErrorResponse(status, data) { const message = data?.message || "Unknown error"; const errorType = data?.error || "unknown_error"; switch (status) { case 400: throw new types_1.ValidationError(message); case 401: throw new types_1.AuthenticationError(message); case 404: throw new types_1.ImagicError(message, 404, "not_found"); case 429: throw new types_1.ImagicError(message, 429, "rate_limit_exceeded"); case 500: throw new types_1.ImagicError(message, 500, "server_error"); default: throw new types_1.ImagicError(message, status, errorType); } } } exports.ImagicClient = ImagicClient; //# sourceMappingURL=client.js.map