Files
Picsur/backend/src/managers/imagemanager/imagemanager.service.ts

52 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-02-21 22:17:44 +01:00
import { Injectable } from '@nestjs/common';
2022-02-21 22:36:47 +01:00
import { fileTypeFromBuffer, FileTypeResult } from 'file-type';
import { ImageEntity } from 'src/collections/imagedb/image.entity';
import { ImageDBService } from 'src/collections/imagedb/imagedb.service';
import { FullMime, MimesService } from 'src/collections/imagedb/mimes.service';
import { AsyncFailable, Fail, HasFailed } from 'src/types/failable';
2022-02-21 22:17:44 +01:00
@Injectable()
2022-02-21 23:19:10 +01:00
export class ImageManagerService {
2022-02-21 22:17:44 +01:00
constructor(
2022-02-21 22:36:47 +01:00
private readonly imagesService: ImageDBService,
2022-02-21 22:17:44 +01:00
private readonly mimesService: MimesService,
) {}
2022-02-23 11:10:25 +01:00
public async retrieve(hash: string): AsyncFailable<ImageEntity> {
if (!this.validateHash(hash)) return Fail('Invalid hash');
return await this.imagesService.findOne(hash);
}
public async upload(image: Buffer): AsyncFailable<string> {
const fullMime = await this.getFullMimeFromBuffer(image);
2022-02-21 22:17:44 +01:00
if (HasFailed(fullMime)) return fullMime;
2022-02-23 11:10:25 +01:00
const processedImage: Buffer = await this.process(image, fullMime);
2022-02-21 22:17:44 +01:00
const imageEntity = await this.imagesService.create(
processedImage,
fullMime.mime,
);
if (HasFailed(imageEntity)) return imageEntity;
return imageEntity.hash;
}
2022-02-23 11:10:25 +01:00
private async process(image: Buffer, mime: FullMime): Promise<Buffer> {
2022-02-21 22:17:44 +01:00
return image;
}
2022-02-23 11:10:25 +01:00
private async getFullMimeFromBuffer(image: Buffer): AsyncFailable<FullMime> {
const mime: FileTypeResult = await fileTypeFromBuffer(image);
const fullMime = await this.mimesService.getFullMime(
mime?.mime ?? 'extra/discard',
);
return fullMime;
2022-02-21 22:17:44 +01:00
}
2022-02-23 11:10:25 +01:00
public validateHash(hash: string): boolean {
2022-02-21 22:17:44 +01:00
return /^[a-f0-9]{64}$/.test(hash);
}
}