More util methods

Some more methods for the storage service.

Before finishing the StorageService, let's just add two more methods there. Going back to it, we may write methods's signatures to:

  • Validate the amount of files to be saved into a directory

  • Generate a unique filename from the original one

abstract validateFilecount(count: number, max: number): void;
abstract genUniqueFilename(filename: string): string;

And now, in the FseService, implement them.

  • validateFilecount() - Checks if the file count exceeds a maximum

validateFilecount(count: number, max: number) {
  if (count > max) {
    throw new ConflictException('File count exceeds max limit');
  }
}
  • genUniqueFilename() - Prepends a filename with a unique prefix

genUniqueFilename(filename: string) {
  const uniquePrefix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
  return `${uniquePrefix}-${filename}`;
}

The unique prefix was obtained from the Multer docs.

It's a good practice to save files with unique filenames.

Lastly, adjust the saveFile() method to use the unique filename.

async saveFile(path: string, file: Express.Multer.File) {
  const { originalname, buffer } = file;

  const uniqueFilename = this.genUniqueFilename(originalname);
  const fullPath = join(BASE_PATH, path, uniqueFilename);
  await writeFile(fullPath, buffer);
}

Commit - Some more features in file storage

Last updated