Reputation: 793
After storing my images separately as strings in postgres. when i go to the route, images looks like this (the response i am currently getting)
"images":"image1.png-2020-11-11T13:15:55.692Z"
i am trying to get it like this
"images":["url":"image1.png-2020-11-11T13:15:55.692Z_full","thumbnailUrl":"image1.png-2020-
11-11T13:15:55.692Z_thumb"]
Here is my get request
router.get("/", (req, res) =>
Post.findAll({
order: [["createdAt", "DESC"]],
include: { model: Post_Image, attributes: ["id", "images"] },
}).then((posts) => {
const baseUrl = config.get("assetsBaseUrl");
for (let post of posts) {
const postImages = post.Post_Images;
const img = postImages.map((post) => post.dataValues);
const imgFileName = img.map((post) => post.images);
const IMAGES = imgFileName.map((image) => ({
url: `${baseUrl}${image}_full.jpg`,
thumbnailUrl: `${baseUrl}${image}_thumb.jpg`,
}));
console.log(IMAGES)
}
res.send(posts);
});
});
when i do console.log(IMAGES), here is my response
[
{
url: 'http://LOCALHOST:PORT/assets/image1.png-2020-11-11T13:15:55.692Z_full.jpg',
thumbnailUrl: 'http://LOCALHOST:PORT/assets/image1.png-2020-11-
11T13:15:55.692Z_thumb.jpg'
}
]
i was trying to do
return{
...post,
images:IMAGES}
but it did not work.
Here is the response i am expecting to get from my get request when i go to the route:
"images": [{"url":"http://192.168.1.103:9000/assets/jacket1_full.jpg","thumbnailUrl" :"http://192.168.1.103:9000/assets/jacket1_thumb.jpg"}]
Upvotes: 1
Views: 308
Reputation: 22783
You should turn Post
model instances into plain objects and add images
prop to each of them:
const plainPosts = posts.map(x => x.get({ plain: true }))
const resultPosts = []
for (const post of plainPosts) {
const { Post_Images, ...postAttributes } = post
const IMAGES = Post_Images.map((postImage) => ({
url: `${baseUrl}${postImage.images}_full.jpg`,
thumbnailUrl: `${baseUrl}${postImage.images}_thumb.jpg`,
}));
console.log(IMAGES)
resultPosts.push({
...postAttributes,
images: IMAGES
})
}
res.send(resultPosts);
if you get a single post only then this should look like:
const plainPost = post.get({ plain: true })
const { Post_Images, ...postAttributes } = plainPost
const IMAGES = Post_Images.map((postImage) => ({
url: `${baseUrl}${postImage.images}_full.jpg`,
thumbnailUrl: `${baseUrl}${postImage.images}_thumb.jpg`,
}));
console.log(IMAGES)
res.send({
...postAttributes,
images: IMAGES
});
Upvotes: 1