deepinfra
Version:
Official API wrapper for DeepInfra
83 lines (82 loc) • 2.73 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReadStreamUtils = void 0;
const node_fs_1 = __importDefault(require("node:fs"));
const axios_1 = __importDefault(require("axios"));
const stream_1 = require("stream");
/**
* Utility class for working with images.
* @class
* @category Utils
* @hideconstructor
*/
exports.ReadStreamUtils = {
/**
* Creates a ReadableStream from a Buffer.
* @param buffer - The Buffer to be streamed.
* @returns A ReadableStream.
*/
bufferToStream(buffer) {
const stream = new stream_1.Readable();
stream.push(buffer);
stream.push(null); // Signifies the end of the stream.
return stream;
},
/**
* Creates a ReadableStream from a file path.
* @param filePath - The path to the image file.
* @returns A ReadableStream of the file contents.
*/
fileToStream(filePath) {
return node_fs_1.default.createReadStream(filePath);
},
/**
* Downloads an image from a URL and returns it as a ReadableStream.
* @param url - The URL of the image.
* @returns A ReadableStream containing the image data.
*/
async urlToStream(url) {
const response = await axios_1.default.get(url, { responseType: "stream" });
return response.data;
},
/**
* Converts a Base64 string to a ReadableStream.
* @param base64 - The Base64 string to be converted.
* @returns A ReadableStream of the image data.
* @throws {Error} If the Base64 string is invalid.
*/
base64ToStream(base64) {
const buffer = Buffer.from(base64, "base64");
return this.bufferToStream(buffer);
},
/**
* Returns a ReadableStream from an object.
* The object can be a Buffer, a file path, or a URL.
* @param input
* @returns A ReadableStream of the image data.
* @throws {Error} If the input type is invalid.
*/
async getReadStream(input) {
if (Buffer.isBuffer(input)) {
return this.bufferToStream(input);
}
else if (typeof input === "string") {
if (input.startsWith("http")) {
return this.urlToStream(input);
}
else if (input.startsWith("data:")) {
const base64Data = input.split(",")[1];
return this.base64ToStream(base64Data);
}
else {
return this.fileToStream(input);
}
}
else {
throw new Error("Invalid input type");
}
},
};