imgUrl을 여러개 입력받아 배열형태로 반환되도록 해야한다.
처음 map메소드를 사용해서 하나의 칸 안에 담을 수 있을까 했다.
const imgPromises = req.files.map(async (file) => {
const imgName = randomImgName();
const params = {
Bucket: bucketName,
Key: imgName,
Body: file.buffer,
ContentType: file.mimetype,
};
const command = new PutObjectCommand(params);
await s3.send(command);
return imgName;
});
const posts = await prisma.posts.create({
data: {
content,
likeCount: +likeCount,
User: { connect: { userId: +user.userId } },
Category: { connect: { categoryId: +category.categoryId } },
Location: { connect: { locationId: +location.locationId } },
imgUrl: imgNames, // imgUrl을 배열로 저장
},
});
하려 했으나 아래와 같이 에러가 생겼다.

문자열을 받는 타입인 imgUrl을 배열형태로 담아서 생긴 에러인데 이 에러를 해결한다고 imgNames.join(",")를 하여 문자열로 바꾼다면 추후 조회되는 imgUrl은 기존 파일명에서 변경이 되어서 원하는 이미지파일을 S3에서 불러오지 못하게된다.
JSON의 속성타입도 고려해봤으나 추후 쿼리 조회로 가득찬 프로젝트로 불편함이 너무 클 것 같아 배제했다.
https://velog.io/@effirin/DB%EC%97%90-JSON-%EC%A0%80%EC%9E%A5%ED%95%98%EA%B8%B0
배열을 담을 수 없다면 그럼 하나의 튜플에 하나씩 담고, 조회할 때 LocationId(사용자가 게시물 작성할 때마다 게시물 기준으로 LocationId가 새로 생성된다) 기준으로 찾아서 반환해주면 안될까했지만,,, 프론트에서 원하는건 배열안에 담는 방법이기때문에 나도 그렇게 반환해줘야만 한다.
결국 post하는 api에서는 위와 같이 작성 후에 조회에서 배열로 담는 방법을 생각했다. 우선 흐름에 대해서 생각해봤다.
2,3번을 map을 이용하여 url을 반복문을 돌려서 s3의 이미지를 찾고,
그걸 또 map을 이용하여 urls를 찾고,
posts의 imgUrl에 대입했다.
/* 게시물 조회 */
router.get("/posts", async (req, res, next) => {
try {
const posts = await prisma.posts.findMany({
select: {
User: {
select: {
nickname: true,
imgUrl: true
}
},
Location: {
select: {
storeName: true,
address: true,
starAvg: true
}
},
imgUrl: true,
content: true,
likeCount: true
},
orderBy: { createdAt: 'desc' },
take: 5
});
if (!posts) { //추가
return res.status(400).json({ message: "존재하지 않는 게시글입니다." })
}
const imgUrlsArray = posts.map(post => post.imgUrl.split(','));
const paramsArray = imgUrlsArray.map(urls => {
return urls.map(url => ({
Bucket: bucketName,
Key: url
}));
});
const signedUrlsArray = await Promise.all(
paramsArray.map(async (params) => {
const commands = params.map(param => new GetObjectCommand(param));
const urls = await Promise.all(commands.map(command => getSignedUrl(s3, command, { expiresIn: 3600 })));
return urls;
})
);
for (let i = 0; i < posts.length; i++) {
posts[i].imgUrl = signedUrlsArray[i];
}
return res.status(200).json(posts);
} catch (error) {
next(error); //추가
}
});
