How to change status code of a response in NodeJS?

1.2k views Asked by At

I'm developing an API in NodeJS that takes the request body of my client to make another request to Brazilian mailing service's API, and then, I give the response to my client in a specific format. The problem is: When the delivery isn't available in the zipcode my client put, the status code that I get from the mail API (and the one I give to the client) is 200. But it is required from me a status code 400. Can I change the status code in NodeJS?

Code below:

'use strict';

const soapRequest = require('easy-soap-request');
var convert = require('xml-js');

//Create the POST Method
exports.post = (req, res) => {
    //Define the parameters for the XML
    for (x in req.body.items.length) {
        var width = req.body.items[x].dimensions.width * 100;
        var height = req.body.items[x].dimensions.height * 100;
        var weight = req.body.items[x].dimensions.weight;
        var depth = req.body.items[x].dimensions.depth * 100;
        var quantity = req.body.items[x].quantity;
        var sku = req.body.items[x].sku;
    };
    var sellerZipcode = '05036123';
    var clientZipcode = req.body.zipcode;

    //Define data for the XML
    const xmlUrl = 'http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx';
    const sampleHeaders = {
    'Content-Type': 'text/xml'
    };

    switch (true) {
        case (height >= weight) && (height >= depth):
            height = height * quantity;
            var lowDim = height;
        case (weight >= height) && (weight >= depth):
            weight = weight * quantity;
            var lowDim = weight;
        case (depth >= weight) && (depth >= height):
            depth = depth * quantity;
            var lowDim = depth;
        };

    // The XML itself
    var xmlFile = '<?xml version="1.0" encoding="utf-8"?>' +
    '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
    '<soap:Body><CalcPrecoPrazo xmlns="http://tempuri.org/">' +
    '<nCdEmpresa>Cant show</nCdEmpresa>' +
    '<sDsSenha>Cant show</sDsSenha>' +
    '<nCdServico>04138</nCdServico>' +
    '<sCepOrigem>' + sellerZipcode + '</sCepOrigem>' +
    '<sCepDestino>' + clientZipcode + '</sCepDestino>' +
    '<nVlPeso>' + weight + '</nVlPeso>' +
    '<nCdFormato>1</nCdFormato>' +
    '<nVlComprimento>' + depth + '</nVlComprimento>' +
    '<nVlAltura>' + height + '</nVlAltura>' +
    '<nVlLargura>' + width + '</nVlLargura>' +
    '<nVlDiametro>' + lowDim + '</nVlDiametro>' +
    '<sCdMaoPropria>N</sCdMaoPropria>' +
    '<nVlValorDeclarado>0</nVlValorDeclarado>' +
    '<sCdAvisoRecebimento>N</sCdAvisoRecebimento>' +
    '</CalcPrecoPrazo></soap:Body></soap:Envelope>';

    //Send the request and takes the response
    async function makeRequest() {
        const { response } = await soapRequest({ url: xmlUrl, headers: sampleHeaders, xml: xmlFile});
        const { headers, body, statusCode} = response;
        var xml = response.body;
        var str = convert.xml2json(xml, {compact: true, spaces: 4, ignoreDeclaration: true, ignoreInstruction: true, ignoreAttributes: true, ignoreDoctype: true, });
        var json = JSON.parse(str);
        return await json;
    };

    //Show error message if there is one, otherwise, show the expected response
    makeRequest().then(json => {
        var json = json["soap:Envelope"]["soap:Body"]["CalcPrecoPrazoResponse"]["CalcPrecoPrazoResult"]["Servicos"]["cServico"];
        var erro = json["MsgErro"];        

        if (erro.hasOwnProperty("_text")){
            res.status(200).send(erro);
        } else { 

            var valor = json["Valor"]["_text"];
            var prazo = json["PrazoEntrega"]["_text"];
            var codigo = json["Codigo"]["_text"];
            var servico = 'SEDEX';

            var str = '{"packages":[{' +
                                '"items":[{' +
                                    '"sku":"' + sku + '",' +
                                    '"quantity":"' + quantity +
                                '"}],' +
                                '"delivery_options":[{' +
                                    '"id":"' + codigo + '",' +
                                    '"type":"Entrega normal",' +
                                    '"name":"' + servico + '",' +
                                    '"price":"' + valor + '",' +
                                    '"delivery_days":"' + prazo + '"}]' +
                                '}]}';

            var response = JSON.parse(str);
            response.packages[0].delivery_options[0].delivery_days = parseInt(response.packages[0].delivery_options[0].delivery_days);
            response.packages[0].items[0].quantity = parseInt(response.packages[0].items[0].quantity);
            //Response with status 200
            res.status(200).send(response);
        };
    });
}
0

There are 0 answers