Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { Storage } from '@google-cloud/storage';
import { Injectable } from '@nestjs/common';
import { type Company } from '@amalia/core/models';
import { FilePathBuilder } from './builders/file-path.builder';
@Injectable()
export class CloudStorageUploadService {
public constructor(private readonly storage: Storage) {}
/**
* Upload a UInt8Array to a bucket
*/
public async uploadUInt8ArrayToBucket(
company: Pick<Company, 'id'>,
data: Uint8Array,
{
bucketName,
folder,
fileName,
contentType = 'application/octet-stream',
isPublic = false,
}: {
bucketName: string;
folder: string;
fileName: string;
contentType?: string;
isPublic?: boolean;
},
) {
const bucket = this.storage.bucket(bucketName);
const filePath = FilePathBuilder.forCompany(company).withFolder(folder).withFileName(fileName).build();
const file = bucket.file(filePath);
const fileBuffer = Buffer.from(data);
await file.save(fileBuffer, {
metadata: {
contentType,
},
public: isPublic,
validation: 'md5',
});
return `https://storage.googleapis.com/${bucketName}/${filePath}`;
}
/**
* Delete a file from a bucket by its URL
*/
public async deleteFileByUrl(fileUrl: string): Promise<void> {
const url = new URL(fileUrl);
const pathParts = url.pathname.slice(1).split('/');
const bucketName = pathParts[0];
const filePath = pathParts.slice(1).join('/');
const bucket = this.storage.bucket(bucketName);
const file = bucket.file(filePath);
await file.delete();
}
/**
* Upload file to GCP cloud storage bucket.
*/
public async uploadImageToBucket(
company: Pick<Company, 'id'>,
image: string,
{
bucketName,
folder,
fileName,
isPublic = false,
}: {
bucketName: string;
folder: string;
fileName: string;
isPublic?: boolean;
},
) {
const bucket = this.storage.bucket(bucketName);
const filePath = FilePathBuilder.forCompany(company).withFolder(folder).withFileName(fileName).build();
const file = bucket.file(filePath);
const imageBase64Content = image.replace(/^data:image\/[^;]+;base64,/u, '');
const imageBuffer = Buffer.from(imageBase64Content, 'base64');
await file.save(imageBuffer, {
metadata: { contentType: 'image/jpeg' },
public: isPublic,
validation: 'md5',
});
return `https://storage.googleapis.com/${bucketName}/${filePath}`;
}
}
|