@aprilnea/nest-file-fastify
Version:
fastify-multipart decorators for Nest.js
76 lines • 3.32 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiskStorage = void 0;
const os_1 = require("os");
const path_1 = require("path");
const fs_1 = require("fs");
const promises_1 = require("fs/promises");
const fs_2 = require("../fs");
const stream_1 = require("../stream");
// Function to execute a storage handler, which can be a function or a string
const excecuteStorageHandler = (file, req, obj) => {
if (typeof obj === "function") {
return obj(file, req); // Execute the function if obj is a function
}
if (obj != null)
return obj; // Return obj if it is not null
return null; // Return null if obj is undefined
};
// Environment variable for test storage path
const ENV_TESTS_STORAGE_TMP_PATH = process.env.__TESTS_TMP_PATH__;
// Class implementing the Storage interface for disk storage
class DiskStorage {
constructor(options) {
this.options = options;
// Override the destination option if the environment variable is set
if (ENV_TESTS_STORAGE_TMP_PATH != null) {
this.options = { ...this.options, dest: ENV_TESTS_STORAGE_TMP_PATH };
}
}
// Method to handle file upload and store it on disk
async handleFile(file, req) {
// Get the filename and destination directory
const filename = await this.getFilename(file, req, this.options?.filename);
const dest = await this.getFileDestination(file, req, this.options?.dest);
// Create the destination directory if it doesn't exist
if (!(await (0, fs_2.pathExists)(dest))) {
await (0, promises_1.mkdir)(dest, { recursive: true });
}
// Create the full path for the file
const path = (0, path_1.join)(dest, filename);
const stream = (0, fs_1.createWriteStream)(path); // Create a writable stream for the file
// Pump the file data into the writable stream
await (0, stream_1.pump)(file.file, stream);
// Destructure necessary properties from the file object
const { encoding, fieldname, mimetype } = file;
// Return an object representing the stored file
return {
size: stream.bytesWritten,
dest,
filename,
originalFilename: file.filename,
path,
mimetype,
encoding,
fieldName: fieldname, // Field name in the form
};
}
// Method to remove a stored file
async removeFile(file, force) {
// Check if the file should be removed based on options or force flag
if (!this.options?.removeAfter && !force)
return;
// Remove the file from the file system
await (0, promises_1.unlink)(file.path);
}
// Protected method to get the filename, either from a handler or generate a unique name
async getFilename(file, req, obj) {
return (excecuteStorageHandler(file, req, obj) ?? (0, fs_2.getUniqueFilename)(file.filename));
}
// Protected method to get the file destination, either from a handler or use the system's temp directory
async getFileDestination(file, req, obj) {
return excecuteStorageHandler(file, req, obj) ?? (0, os_1.tmpdir)();
}
}
exports.DiskStorage = DiskStorage;
//# sourceMappingURL=disk-storage.js.map