FilesystemBackend: Implement deleteFile and getFileURL.

We use `fs.unlink` instead of `fs.rm`, as the latter is only available in the fsPromises API since Node 14.14

Signed-off-by: David Mehren <git@herrmehren.de>
This commit is contained in:
David Mehren 2020-10-17 16:24:30 +02:00
parent 9743018591
commit 3da16baeae
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
3 changed files with 35 additions and 13 deletions

View file

@ -1,26 +1,39 @@
import { MediaBackend } from '../media-backend.interface';
import { BackendData } from '../media-upload.entity';
import { Injectable } from '@nestjs/common';
import { promises as fs } from 'fs';
import { join } from 'path';
import { ConsoleLoggerService } from '../../logger/console-logger.service';
import { MediaBackend } from '../media-backend.interface';
import { BackendData } from '../media-upload.entity';
@Injectable()
export class FilesystemBackend implements MediaBackend {
constructor(private readonly logger: ConsoleLoggerService) {
this.logger.setContext(FilesystemBackend.name);
}
async saveFile(
buffer: Buffer,
fileName: string,
): Promise<[string, BackendData]> {
// TODO: Get uploads directory from config
const uploadDirectory = './uploads';
// TODO: Add server address to url
const filePath = join(uploadDirectory, fileName);
const filePath = FilesystemBackend.getFilePath(fileName);
this.logger.debug(`Writing file to: ${filePath}`, 'saveFile');
await fs.writeFile(filePath, buffer, null);
return ['/' + filePath, null];
}
deleteFile(fileName: string, backendData: BackendData): Promise<void> {
return Promise.resolve(undefined);
async deleteFile(fileName: string, backendData: BackendData): Promise<void> {
return fs.unlink(FilesystemBackend.getFilePath(fileName));
}
getFileURL(fileNam: string, backendData: BackendData): Promise<string> {
return Promise.resolve('');
getFileURL(fileName: string, backendData: BackendData): Promise<string> {
const filePath = FilesystemBackend.getFilePath(fileName);
// TODO: Add server address to url
return Promise.resolve('/' + filePath);
}
private static getFilePath(fileName: string): string {
// TODO: Get uploads directory from config
const uploadDirectory = './uploads';
return join(uploadDirectory, fileName);
}
}