๐Client์์ ํ์ผ์ ์ ๋ก๋ํ๋ฉด Server๋ Google Storage์ ํ์ผ์ ์ ๋ก๋ํ๊ณ ํ์ผ์ ๋ํ ์ ๋ณด๋ฅผ Database์ ์ ์ฅ
[Google Storage์ ์ ์ฅํ๋ ๋ก์ง ์์]
yarn add graphql-upload
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './commons/filter/http-exception.filter';
import * as dotenv from 'dotenv';
import * as cors from 'cors';
import { graphqlUploadExpress } from 'graphql-upload';
dotenv.config();
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new HttpExceptionFilter());
app.use(graphqlUploadExpress());
app.use(cors());
await app.listen(3000);
}
bootstrap();
// file.resolver
import { Args, Mutation, Resolver } from '@nestjs/graphql';
import { FileService } from './file.service';
import { FileUpload, GraphQLUpload } from 'graphql-upload';
@Resolver()
export class FileResolver {
constructor(
private readonly fileService: FileService, //
) {}
@Mutation(() => [String])
async uploadCarFile(
@Args({ name: 'files', type: () => [GraphQLUpload] }) files: FileUpload[],
) {
return await this.fileService.upload({ files });
}
}
//file.service
import { Injectable } from '@nestjs/common';
import { Storage } from '@google-cloud/storage';
import { FileUpload } from 'graphql-upload';
import { getToday } from 'src/commons/libraries/utils';
import { v4 as uuidv4 } from 'uuid';
interface IFile {
files: FileUpload[]; //
}
@Injectable()
export class FileService {
async upload({ files }: IFile) {
const storage = new Storage({
keyFilename: process.env.KEY_FILENAME,
projectId: process.env.PROJECT_ID,
}).bucket('codecamp-file-storage1');
// ํ์ผ ๋จผ์ ๋ค ๋ฐ์๋๊ธฐ
const waitedFiles = await Promise.all(files);
const results = await Promise.all(
waitedFiles.map((el) => {
return new Promise((resolve, reject) => {
const fname = `${getToday()}/${uuidv4}/orgin/${el.filename}`; // uuid๋ก ์ค๋ณต์ด๋ฆ ๋ฐฉ์ง ๊ฐ๋ฅ
el.createReadStream()
.pipe(storage.file(el.filename).createWriteStream())
.on('finish', () => {
resolve(`codecamp-file-storage1/${fname}`);
})
.on('error', () => reject());
});
}),
);
console.log(results);
return results;
}
}
new Storage
๋ฅผ ์์ฑํ์ฌ storage๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด ํ์ํ ๊ฐ๋ค์ ๋ฃ๊ธฐ(keyFilename, projectId)
new Promise
๋ฅผ ์ด์ฉํด์ file์ createReadStream()์ ์ฌ์ฉํด์ ํ์ผ์ ์ฝ๊ธฐ
pipe()๋ฅผ ์ด์ฉํด์ 2์ฐจ์ ์ธ ์์ ์คํ(์ฌ์ด์ฆ์กฐ์ , ์ ์ฅ ๋ฑ)
on()์ผ๋ก ๊ฒฐ๊ณผ ๋ํ๋ด๊ธฐ