FilesystemBackend: Ensure uploads directory exists

Signed-off-by: David Mehren <git@herrmehren.de>
This commit is contained in:
David Mehren 2020-10-24 12:28:52 +02:00
parent 4f3ef414d4
commit d42bc83e38
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3

View file

@ -7,33 +7,43 @@ import { BackendData } from '../media-upload.entity';
@Injectable()
export class FilesystemBackend implements MediaBackend {
// TODO: Get uploads directory from config
uploadDirectory = './uploads';
constructor(private readonly logger: ConsoleLoggerService) {
this.logger.setContext(FilesystemBackend.name);
}
private getFilePath(fileName: string): string {
return join(this.uploadDirectory, fileName);
}
private async ensureDirectory() {
try {
await fs.access(this.uploadDirectory);
} catch (e) {
await fs.mkdir(this.uploadDirectory);
}
}
async saveFile(
buffer: Buffer,
fileName: string,
): Promise<[string, BackendData]> {
const filePath = FilesystemBackend.getFilePath(fileName);
const filePath = this.getFilePath(fileName);
this.logger.debug(`Writing file to: ${filePath}`, 'saveFile');
await this.ensureDirectory();
await fs.writeFile(filePath, buffer, null);
return ['/' + filePath, null];
}
async deleteFile(fileName: string, _: BackendData): Promise<void> {
return fs.unlink(FilesystemBackend.getFilePath(fileName));
return fs.unlink(this.getFilePath(fileName));
}
getFileURL(fileName: string, _: BackendData): Promise<string> {
const filePath = FilesystemBackend.getFilePath(fileName);
const filePath = this.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);
}
}