โฌ๏ธ Main Note
https://docs.google.com/document/d/16tOFT5iZlWc_uvNHrHL-w3Eynet1ktGHwoLee-Pbm_E/edit
When user uploads a file, that image file is saved into storage service and the image url, which is in string form, is saved in database.
This URL type is called BLOB type.
โค Binary Large Object Data : Data that's converted into binary code
The file itself isn't saved, but the pixelized Blob is saved.
- If we zoom in the image close as we can, the we can see the little pixels. Those pixel's RGB is converted as binary code and that's the way how it works.
import { Injectable } from '@nestjs/common';
import { Storage } from '@google-cloud/storage';
import { FileUpload } from 'graphql-upload';
interface IFile {
files: FileUpload[];
}
@Injectable()
export class FileService {
async upload({ files }: IFile) {
// storage์ ํ์ผ ์ ์ฅ
const myStorage = new Storage({
// 2. ํ์ผ์ ์์ฑํ๊ณ
keyFilename: process.env.KEY_FILE_NAME,
projectId: 'wise-invention-347011',
}).bucket('main-project-files-bucket'); // ์ด ํด๋์ ์ ์ฅํด์ค
// .file(file.filename); // ์ด ์ด๋ฆ์ผ๋ก
// ** ์ผ๋จ ๋จผ์ ๋ค ๋ฐ๊ธฐ **
const waitedFiles = await Promise.all(files);
// files === [file, file, file, file, ...]
const results = await Promise.all(
// [promise, promise, promise, ...] ==> [url, url, url, ...]
waitedFiles.map((el) => {
// element == ํ์ผ ํ๋ํ๋
return new Promise((resolve, reject) => {
el.createReadStream() // 3. ์ฝ์ด๋ค์ด๋๊ฑฐ์
.pipe(myStorage.file(el.filename).createWriteStream()) // ์ด storage์ ๋ฃ์ด์ค! ํ๋๊ฑฐ์ // ๊ทธ๋ผ ์์ค์์ ์ฝ์ด์จ ํ์ผ์ writeํ๋๊ฑฐ ๊ทธ๋์ ์คํจ ์ฑ๊ณต ์ฌ๋ถ ๋ฐ์ง๊ธฐ // ์ด ํ์ผ์ ์ด๋ฆ์ผ๋ก ์ฝ๊ฒ ๋ค
.on('finish', () => resolve(`wise-invention-347011/${el.filename}`)) // ๋๋๋ฉด ์ด๊ฑฐ ์คํ์์ผ์ค (์ด๋ฏธ์ง URL ํ๋ก ํธ์ ๋ฑ๊ธฐ)
.on('error', () => reject('์คํจ')); // ์๋ฌ๋๋ฉด ์ด๊ฑฐ ์คํ์์ผ์ค
// ํ์ผ ์คํ์์ผ์ ์ฝ์ด์ฃผ๊ธฐ => createReadStream
// ์ฝ์ด๋ค์ธ ํ์ผ๋ก 2์ฐจ ์์
์ ํ ๋ => pipe() ์ฌ์ฉ (์ฝ์ ํ์ผ์ ์ฌ์ด์ฆ๋ ํ์ง์ ์กฐ์ ํ๋ค๊ณ ํ๋๊ฒ)
});
}),
);
// commit test test test
return results; // finish์์ ์ฑ๊ณตํ๊ฒ ๋๋ฉด frontend๋ก ๋ฆฌํดํด์ค์ผํจ // URL ์ถ๋ ฅ
}
}
// await ๋ฅผ ๋ถ์ผ ์ ์๋๊ฑด promise์ ํ์์
Once the image is uploaded, cloud function automatically executes its function. ex) Enlarging or compressing the size of image
Cloud Function is called Thumbnail Trigger
โค According to the image, it automatically shrinks the size of image.
After recreating the image as a new size, it re-stores into storage.