Search code examples
javascriptaxiosstrapi

Strapi closing connection to host before response


I have a local Java Service that exposes a single endpoint where the response can take over 5min sometimes depending on the request size. I want to "hide" this endpoint behind Strapi, so that a user that is not authenticated through Strapi, can't access this endpoint. What i've done is, created a custom Route in Strapi, and created a custom controller function for this route:

async optimizeRoute(ctx) {
    try {
        console.log(`${new Date()} - Optimize route started`)
        const vehicles = ctx.request.body.vehicles.map(vehicle => {
            return {
                id: vehicle.id,
                licenseplate: vehicle.licenseplate,
                maxweight: vehicle.maxweight,
                maxlength: vehicle.maxlength,
                geojson: vehicle.geojson,
                maxtime: moment(vehicle.endtime).diff(moment(vehicle.starttime), 'seconds') * 1.1
            }
        });

        const orders = ctx.request.body.orders.map(order => {
            return {
                id: order.id,
                weight: order.weight,
                length: order.length,
                geojson: order.geojson
            }
        });
        console.log(`Using ${vehicles.length} vehicles, and ${orders.length} orders!`)
        const response = await axios.post('http://127.0.0.1:9090/optimizeroutes',
            { vehicles: vehicles, orders: orders }, {timeout: 0}
        );
        return response.data;
    } catch (error) {
        ctx.throw(error.response.status, error.response);
    }
}

But what happens when i do this, is Strapi closes the connection after 1-2 min to the requester before the response is returned. Using Strapi Beta3.17.5. Anywhere i can configure or debug to wait for the axios to return a response then return the response to the requester??


Solution

  • The default server timeout value is 2 min, Please check the image for reference. enter image description here

    So in server.js you can increase this timeout value by passing callback function

    So the code will look like below

    const strapi = require('strapi');
    
    strapi(/* {...} */).start(()=>{
    
        strapi.server.setTimeout(0); 
    });
    
    

    setting timeout to 0 strapi will wait forever or you can add value in milliseconds.