Upload images for an event using Cloudinary API

放肆的年华 提交于 2019-12-24 10:36:58

问题


Below is my API endpoint for creating an event in my application. I'm also using Cloudinary API for uploading my images and storing the returned URL into my database.

app.post('/event', (req, res) => {
    try {
        if (req.body.images.length > 0) {
           // Creating new Event instance
            const event = new Event({
                title: req.body.title,
                images: [],
            });

           // Looping over every image coming in the request object from frontend
            req.body.images.forEach((img) => {
                const base64Data = img.content.split(',')[1];

            // Writing the images in upload folder for time being 
                fs.writeFileSync(`./uploads/${img.filename}`, base64Data, 'base64', (err) => {
                    if (err) {
                        throw err;
                    }
                });

              /* Now that image is saved in upload folder, Cloudnary picks 
             the image from upload folder and store it at their cloud space.*/
                cloudinary.uploader.upload(`./uploads/${img.filename}`, async (result) => {

                 // Cloudnary returns id & URL of the image which is pushed into the event.images array.
                    event.images.push({
                        id: result.public_id,
                        url: result.secure_url
                    });

                 // Once image is pushed into the array, I'm removing it from my server's upload folder using unlinkSync function
                    fs.unlinkSync(`./uploads/${img.filename}`);

       // When all the images are uploaded then I'm sending back the response
                    if (req.body.images.length === event.images.length) {
                        await event.save();
                        res.send({
                            event,
                            msg: 'Event created successfully'
                        });
                    }
                });
            });
        }
    } catch (e) {
        res.status(400).send(e);
    }
});

Now My question is how can I convert the above code into more efficient and short?

来源:https://stackoverflow.com/questions/52588060/upload-images-for-an-event-using-cloudinary-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!