default-asset-storage-strategy.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { INestApplication, INestExpressApplication } from '@nestjs/common';
  2. import { Request } from 'express';
  3. import * as fs from 'fs-extra';
  4. import * as path from 'path';
  5. import { Stream } from 'stream';
  6. import { AssetStorageStrategy } from '../../config/asset-storage-strategy/asset-storage-strategy';
  7. /**
  8. * A persistence strategy which saves files to the local file system.
  9. */
  10. export class DefaultAssetStorageStrategy implements AssetStorageStrategy {
  11. private uploadPath: string;
  12. constructor(uploadDir: string = 'assets') {
  13. this.setAbsoluteUploadPath(uploadDir);
  14. }
  15. writeFileFromStream(fileName: string, data: Stream): Promise<string> {
  16. const filePath = path.join(this.uploadPath, fileName);
  17. const writeStream = fs.createWriteStream(filePath, 'binary');
  18. return new Promise<string>((resolve, reject) => {
  19. data.pipe(writeStream);
  20. writeStream.on('close', () => resolve(this.filePathToIdentifier(filePath)));
  21. writeStream.on('error', reject);
  22. });
  23. }
  24. async writeFileFromBuffer(fileName: string, data: Buffer): Promise<string> {
  25. const filePath = path.join(this.uploadPath, fileName);
  26. await fs.writeFile(filePath, data, 'binary');
  27. return this.filePathToIdentifier(filePath);
  28. }
  29. readFileToBuffer(identifier: string): Promise<Buffer> {
  30. return fs.readFile(this.identifierToFilePath(identifier));
  31. }
  32. readFileToStream(identifier: string): Promise<Stream> {
  33. const readStream = fs.createReadStream(this.identifierToFilePath(identifier), 'binary');
  34. return Promise.resolve(readStream);
  35. }
  36. toAbsoluteUrl(request: Request, identifier: string): string {
  37. return `${request.protocol}://${request.get('host')}/${identifier}`;
  38. }
  39. private setAbsoluteUploadPath(uploadDir: string): string {
  40. this.uploadPath = uploadDir;
  41. if (!fs.existsSync(this.uploadPath)) {
  42. fs.mkdirSync(this.uploadPath);
  43. }
  44. return this.uploadPath;
  45. }
  46. private filePathToIdentifier(filePath: string): string {
  47. return `${path.basename(this.uploadPath)}/${path.basename(filePath)}`;
  48. }
  49. private identifierToFilePath(identifier: string): string {
  50. return path.join(this.uploadPath, path.basename(identifier));
  51. }
  52. }