UNPKG

softypy-media-service

Version:

A media upload service client for Node.js and frontend applications

236 lines (229 loc) 7.55 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { MediaService: () => MediaService, configureMediaService: () => configureMediaService, getMediaService: () => getMediaService }); module.exports = __toCommonJS(src_exports); // src/api.ts var import_axios = __toESM(require("axios")); var ApiService = class { constructor(config) { this.client = import_axios.default.create({ baseURL: config.baseUrl, timeout: config.timeout || 3e4, headers: { "x-api-key": config.apiKey } }); this.setupInterceptors(); } setupInterceptors() { this.client.interceptors.response.use( (response) => response, (error) => { var _a, _b; console.error("API Error:", (_a = error == null ? void 0 : error.response) == null ? void 0 : _a.data); return Promise.reject((_b = error == null ? void 0 : error.response) == null ? void 0 : _b.data); } ); } getClient() { return this.client; } }; // src/utils/helpers.ts var createFormData = (file, options) => { const formData = new FormData(); formData.append("file", file); if (options) { if (options.transform) { formData.append("transform", JSON.stringify(options.transform)); } if (options.metadata) { formData.append("metadata", JSON.stringify(options.metadata)); } } return formData; }; // src/utils/validation.ts var validateConfig = (config) => { if (!config.baseUrl) { throw new Error("baseUrl is required in MediaServiceConfig"); } if (!config.apiKey) { throw new Error("apiKey is required in MediaServiceConfig"); } if (config.timeout !== void 0 && config.timeout < 0) { throw new Error("timeout must be a positive number"); } if (config.retryAttempts !== void 0 && config.retryAttempts < 0) { throw new Error("retryAttempts must be a positive number"); } }; var validateTransformOptions = (transform) => { if (transform.width !== void 0 && transform.width < 1) { throw new Error("width must be greater than 0"); } if (transform.height !== void 0 && transform.height < 1) { throw new Error("height must be greater than 0"); } if (transform.quality !== void 0 && (transform.quality < 1 || transform.quality > 100)) { throw new Error("quality must be between 1 and 100"); } if (transform.format !== void 0 && !["jpeg", "png", "webp", "avif"].includes(transform.format)) { throw new Error("format must be one of: jpeg, png, webp, avif"); } if (transform.fit !== void 0 && !["cover", "contain", "fill"].includes(transform.fit)) { throw new Error("fit must be one of: cover, contain, fill"); } }; // src/mediaService.ts var MediaService = class { constructor(config) { validateConfig(config); this.apiService = new ApiService(config); } /** * Upload a file to the media service * @param file The file to upload * @param options Optional transform and metadata options */ async uploadFile(file, options) { try { if (options == null ? void 0 : options.transform) { validateTransformOptions(options.transform); } const formData = createFormData(file, options); const response = await this.apiService.getClient().post("/upload", formData, { headers: { "Content-Type": "multipart/form-data" } }); return response.data; } catch (error) { throw error; } } /** * Get a file by its public ID * @param publicId The public ID of the file * @param transform Optional transformation parameters */ async getFile(publicId, transform) { try { if (transform) { validateTransformOptions(transform); return this.getFileWithTransform(publicId, transform); } const response = await this.apiService.getClient().get(`/${publicId}`); return response.data; } catch (error) { throw error; } } /** * Get the thumbnail version of a file * @param publicId The public ID of the file */ async getThumbnail(publicId) { try { const response = await this.apiService.getClient().get(`/${publicId}/thumbnail`); return response.data; } catch (error) { throw error; } } /** * Get a transformed version of a file * @param publicId The public ID of the file * @param transform The transformation options */ async getTransformedFile(publicId, transform) { try { validateTransformOptions(transform); return this.getFileWithTransform(publicId, transform); } catch (error) { throw error; } } /** * Get a file with custom transformation parameters * @param publicId The public ID of the file * @param transform The transformation options */ async getFileWithTransform(publicId, transform) { const params = new URLSearchParams(); if (transform.width) params.append("w", transform.width.toString()); if (transform.height) params.append("h", transform.height.toString()); if (transform.format) params.append("format", transform.format); if (transform.quality) params.append("q", transform.quality.toString()); if (transform.fit) params.append("fit", transform.fit); const response = await this.apiService.getClient().get(`/${publicId}/transform?${params.toString()}`); return response.data; } /** * Delete a file by its public ID * @param publicId The public ID of the file to delete */ async deleteFile(publicId) { try { const response = await this.apiService.getClient().delete(`/${publicId}`); return response.data; } catch (error) { throw error; } } }; // src/index.ts var mediaService = null; var configureMediaService = (config) => { mediaService = new MediaService(config); return mediaService; }; var getMediaService = () => { if (!mediaService) { throw new Error("MediaService not configured. Call configureMediaService first."); } return mediaService; }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { MediaService, configureMediaService, getMediaService });