nodejs express multer로만 파일 업로드 기능을 구현해오다가
이번에 처음으로 nestjs+graphql 환경에서는 파일 업로드 기능을 구현해봤다.
graphql에서 파일업로드는
graphql-upload
라이브러리를 사용해야했다.에러 발생
- 아래처럼 해줬지만
createReadStream is not a function
이라고 에러가 나왔다.
import { Injectable } from '@nestjs/common'; import * as AWS from 'aws-sdk'; import { IFilesService } from './interfaces/files-service.interface'; @Injectable() export class FilesService { private readonly s3: AWS.S3; constructor() { AWS.config.update({ accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, region: process.env.AWS_REGION, }); this.s3 = new AWS.S3(); } async upload({ userId, files }: IFilesService): Promise<string[]> { const uploadPromises = files.map(async (file) => { const { createReadStream, filename } = file; const stream = createReadStream(); const params = { Bucket: process.env.AWS_BUCKET_NAME, Key: `${userId}/${filename}`, Body: stream, }; const res = await this.s3.upload(params).promise(); return res.Location; }); const response = await Promise.all(uploadPromises); return response; } }
에러 해결
- vscode에서
await file
부분에서 await이 필요없다고 안내해줘서 지웠던 적이 있었는데.. await을 붙여줘야 하는거였다.. 지금도 vscode에선 await이 필요없다고 안내해주고있다..
import { Injectable } from '@nestjs/common'; import * as AWS from 'aws-sdk'; import { IFilesService } from './interfaces/files-service.interface'; @Injectable() export class FilesService { private readonly s3: AWS.S3; constructor() { AWS.config.update({ accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, region: process.env.AWS_REGION, }); this.s3 = new AWS.S3(); } async upload({ userId, files }: IFilesService): Promise<string[]> { const uploadPromises = files.map(async (file) => { const { createReadStream, filename } = await file; // await을 붙여줌 const stream = createReadStream(); const params = { Bucket: process.env.AWS_BUCKET_NAME, Key: `${userId}/${filename}`, Body: stream, }; const res = await this.s3.upload(params).promise(); return res.Location; }); const response = await Promise.all(uploadPromises); return response; } }
댓글