fix(media-upload): rework create and media services saveFile

This was done to make the create method more concise.

Signed-off-by: Philip Molares <philip.molares@udo.edu>
This commit is contained in:
Philip Molares 2021-11-11 22:06:30 +01:00
parent d5c77613bb
commit 09f0d7c389
2 changed files with 24 additions and 16 deletions

View file

@ -3,7 +3,6 @@
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import * as crypto from 'crypto';
import {
Column,
CreateDateColumn,
@ -53,24 +52,32 @@ export class MediaUpload {
// eslint-disable-next-line @typescript-eslint/no-empty-function
private constructor() {}
/**
* Create a new media upload enity
* @param id the id of the upload
* @param note the note the upload should be associated with. This is required despite the fact the note field is optional, because it's possible to delete a note without also deleting the associated media uploads, but a note is required for the initial creation.
* @param user the user that owns the upload
* @param extension which file extension the upload has
* @param backendType on which type of media backend the upload is saved
* @param backendData the backend data returned by the media backend
* @param fileUrl the url where the upload can be accessed
*/
public static create(
id: string,
note: Note,
user: User,
extension: string,
backendType: BackendType,
backendData?: string,
backendData: BackendData | null,
fileUrl: string,
): Omit<MediaUpload, 'createdAt'> {
const upload = new MediaUpload();
const randomBytes = crypto.randomBytes(16);
upload.id = randomBytes.toString('hex') + '.' + extension;
upload.id = id;
upload.note = note;
upload.user = user;
upload.backendType = backendType;
if (backendData) {
upload.backendData = backendData;
} else {
upload.backendData = null;
}
upload.backendData = backendData;
upload.fileUrl = fileUrl;
return upload;
}
}

View file

@ -6,6 +6,7 @@
import { Inject, Injectable } from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { InjectRepository } from '@nestjs/typeorm';
import crypto from 'crypto';
import * as FileType from 'file-type';
import { Repository } from 'typeorm';
@ -88,19 +89,19 @@ export class MediaService {
if (!MediaService.isAllowedMimeType(fileTypeResult.mime)) {
throw new ClientError('MIME type not allowed.');
}
const randomBytes = crypto.randomBytes(16);
const id = randomBytes.toString('hex') + '.' + fileTypeResult.ext;
this.logger.debug(`Generated filename: '${id}'`, 'saveFile');
const [url, backendData] = await this.mediaBackend.saveFile(fileBuffer, id);
const mediaUpload = MediaUpload.create(
id,
note,
user,
fileTypeResult.ext,
this.mediaBackendType,
backendData,
url,
);
this.logger.debug(`Generated filename: '${mediaUpload.id}'`, 'saveFile');
const [url, backendData] = await this.mediaBackend.saveFile(
fileBuffer,
mediaUpload.id,
);
mediaUpload.backendData = backendData;
mediaUpload.fileUrl = url;
await this.mediaUploadRepository.save(mediaUpload);
return url;
}