UNPKG

@zerokurns/unlayer-ts-client

Version:

TypeScript client library for the Unlayer Cloud API

196 lines 9.04 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.UnlayerClient = void 0; const axios_1 = __importDefault(require("axios")); const errors_1 = require("./errors"); /** * Main client for interacting with the Unlayer Cloud API v2. */ class UnlayerClient { /** * Creates an instance of the Unlayer API client. * @param apiKey - Your Unlayer Project API Key. * @param baseURL - Optional base URL for the API (defaults to production v2 URL). * @param timeout - Optional request timeout in milliseconds (defaults to 60000). */ constructor(apiKey, baseURL = 'https://api.unlayer.com/v2', timeout = 60000 // Default timeout of 60 seconds ) { if (!apiKey) { throw new Error('Unlayer API key is required.'); } this.apiKey = apiKey; // Encode API Key for Basic Auth (APIKey + ':') // We use Buffer for Node.js environments. For browser environments, btoa would be needed. // Consider adding a check or separate builds if browser support is primary. const encodedApiKey = Buffer.from(`${this.apiKey}:`).toString('base64'); this.httpClient = axios_1.default.create({ baseURL: baseURL, headers: { 'Authorization': `Basic ${encodedApiKey}`, 'Content-Type': 'application/json', 'Accept': 'application/json', }, timeout: timeout, }); // Optional: Add interceptors for logging or advanced error handling // this.httpClient.interceptors.request.use(config => { // console.log('Starting Request', config); // return config; // }); // this.httpClient.interceptors.response.use(response => { // console.log('Response:', response.status, response.data); // return response; // }); } /** * Private helper method to make requests and handle errors. * @param method - HTTP method ('get', 'post'). * @param path - API endpoint path (e.g., '/templates'). * @param params - Query parameters for GET requests. * @param data - Request body data for POST requests. * @returns Promise resolving to the API response data. */ request(method, path, params, data) { return __awaiter(this, void 0, void 0, function* () { try { const response = yield this.httpClient.request({ method, url: path, params: params, // Axios handles query params serialization data: data // Axios handles JSON body serialization for objects }); // The API consistently wraps responses in { success: boolean, data: ... } // We might want to return response.data directly as the types expect this structure. return response.data; } catch (error) { // Use the centralized error handler which will throw an UnlayerApiError (0, errors_1.handleApiError)(error); // This line is unreachable due to handleApiError always throwing, but satisfies TypeScript throw error; } }); } // --- Export Methods --- /** * Export a design to HTML format. * Corresponds to `POST /export/html` * @param payload - The export options and design JSON. * @returns The exported HTML and associated chunks. * @throws {UnlayerApiError} If the API request fails. * @see https://docs.unlayer.com/reference/export-html # Replace with actual docs link if available */ exportHtml(payload) { return __awaiter(this, void 0, void 0, function* () { return this.request('post', '/export/html', undefined, payload); }); } /** * Export a design to image (PNG) format. * Corresponds to `POST /export/image` * @param payload - The export options and design JSON. * @returns An object containing the URL of the generated image. * @throws {UnlayerApiError} If the API request fails. * @see https://docs.unlayer.com/reference/export-image # Replace with actual docs link if available */ exportImage(payload) { return __awaiter(this, void 0, void 0, function* () { return this.request('post', '/export/image', undefined, payload); }); } /** * Export a design to PDF format. * Corresponds to `POST /export/pdf` * @param payload - The export options and design JSON. * @returns An object containing the URL of the generated PDF. * @throws {UnlayerApiError} If the API request fails. * @see https://docs.unlayer.com/reference/export-pdf # Replace with actual docs link if available */ exportPdf(payload) { return __awaiter(this, void 0, void 0, function* () { return this.request('post', '/export/pdf', undefined, payload); }); } /** * Export a design as a ZIP archive containing HTML and assets. * Corresponds to `POST /export/zip` * @param payload - The export options and design JSON. * @returns An object containing the URL of the generated ZIP archive. * @throws {UnlayerApiError} If the API request fails. * @see https://docs.unlayer.com/reference/export-zip # Replace with actual docs link if available */ exportZip(payload) { return __awaiter(this, void 0, void 0, function* () { return this.request('post', '/export/zip', undefined, payload); }); } // --- Template Methods --- /** * Get a list of available templates, optionally paginated. * Corresponds to `GET /templates` * @param params - Query parameters for pagination and design inclusion. * @returns An object containing a list of templates. * @throws {UnlayerApiError} If the API request fails. * @see https://docs.unlayer.com/reference/list-templates # Replace with actual docs link if available */ listTemplates(params) { return __awaiter(this, void 0, void 0, function* () { // Basic validation for pagination params if ((params === null || params === void 0 ? void 0 : params.page) !== undefined && params.page < 1) { throw new Error('Parameter \'page\' must be >= 1.'); } if ((params === null || params === void 0 ? void 0 : params.perPage) !== undefined && params.perPage < 1) { throw new Error('Parameter \'perPage\' must be >= 1.'); } return this.request('get', '/templates', params); }); } /** * Get a specific template by its ID. * Corresponds to `GET /templates/{id}` * @param id - The ID of the template to retrieve. * @returns The specific template details including the design JSON. * @throws {UnlayerApiError} If the API request fails. * @throws {Error} If the template ID is not provided. * @see https://docs.unlayer.com/reference/get-template # Replace with actual docs link if available */ getTemplate(id) { return __awaiter(this, void 0, void 0, function* () { if (!id) { throw new Error('Template ID is required.'); } return this.request('get', `/templates/${id}`); }); } /** * Render the HTML for a specific template. * Corresponds to `GET /templates/{id}/render` * @param id - The ID of the template to render. * @returns The rendered HTML, chunks, and AMP details. * @throws {UnlayerApiError} If the API request fails. * @throws {Error} If the template ID is not provided. * @see https://docs.unlayer.com/reference/render-template-html # Replace with actual docs link if available */ renderTemplateHtml(id) { return __awaiter(this, void 0, void 0, function* () { if (!id) { throw new Error('Template ID is required.'); } return this.request('get', `/templates/${id}/render`); }); } } exports.UnlayerClient = UnlayerClient; //# sourceMappingURL=client.js.map