Search code examples
expressjson-server

Call multiple DELETE calls from a single POST call in express?


I am using json-server(based on express) and gulp-json-srv in a project. I have the following "customRoute":

'/deletefavorites': {
    method: 'POST',
    handler: function(req, res, next) {
        req.method = 'DELETE';
        var arr = req.body;
        for (var i = 0; i < arr.length; i++) {
            req.url = '/favorites/' + arr[i];
            res.redirect(req.url);
        }
    }
}

The array req.body simply holds ids of "favorites". So the req.body looks something like this:

{[
    "id": "123",
    "id":"124",
    ...
]}

The problem is that redirect only redirects this request once and then errors. Meaning I would only be able to DELETE one record, and it also doesn't handle the "method", because I can only send the URL in a redirect.

What I would want is something like this:

for (var i = 0; i < arr.length; i++) {
    req.url = '/favorites/' + arr[i];
    app.handle(req, res, next);
}    
next();

With the new parameters. Is something like that possible? I've searched through many related stack overflow questions, but the only solution I found was using a xhr request in there, but I figured express should have a way to deal with this?


Solution

  • Here is an example way of calling within the service

    const express = require('express');
    
    const app = express();
    const request = require('request');
    
    app.post('/deleteFavorites', (req, res) => {
        req.body = [
            {"id": "123"},
            {"id":"124"},
        ]
    
        console.log("deleteFavorites was called?")
        request.delete({
            url: "http://" + req.headers.host + "/favorites/delete",
            body: req.body,
            json: true
        }, function(error, response, body){
            console.log(body, error, response);
            res.status(200).send("all good");
        });
    
    });
    
    app.delete('/favorites/delete', (req, res) => {
        console.log("favorites/delete was called?")
        res.status(200).send("all good");
    
    });
    
    app.listen(9090);
    

    The ideal way is to do it through re-usable functions but since you mentioned that is not an option, this is another possible approach one can use.

    But I would recommend to limit it to one call instead of multiple calls, else you may cause a request explosion at the server. If you send 100 ids at server in /deleteFavorites then that would raise too may request at server causing most of them to timeout