Conor
Conor

Reputation: 740

node.js JSON api return structured data

I am creating an API using Node.Js and MySQL and I am trying to structure the data when it is returned.

I am POSTing the following to create a new record

{
    "SiteName" : "My Site",
    "PitchTypes" : {
        "TentPitches": true
    }
}

This creates a new entry into the database correctly and then returns the data. However, it is returning the following. How can I format the data into the same format it was submitted in.

{
    "id": 1,
    "SiteName": "My Site",
    "TentPitches": true
}

I have the following in my model and controller

campsite.models.js

exports.create = (req, res) => {
  // Validate request
  if (!req.body) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
  }
  
  // Create a Record
  const campsite = new Campsite({
    SiteName: req.body.SiteName,
    TentPitches: req.body.PitchTypes.TentPitches
  });
  
  // Save Campsite in the database
  Campsite.create(campsite, (err, data) => {
    if (err)
    res.status(500).send({
      message:
      err.message || "Some error occurred while creating the Campsite."
    });
    else res.send(data);
  });
};

campsite.controllers.js

const Campsite = function(campsite) {
  this.SiteName = campsite.SiteName;
  this.TentPitches = campsite.TentPitches;
  
};

Campsite.create = (newCampsite, result) => {
  sql.query("INSERT INTO campsites SET ?", newCampsite, (err, res) => {
    if (err) {
      console.log("error: ", err);
      result(err, null);
      return;
    }
    
    console.log("created campsite: ", { id: res.insertId, ...newCampsite });
    result(null, { id: res.insertId, ...newCampsite });
  });
};

my MySQL database has the following table

CREATE TABLE `campsites` (
    `Id` int(5) NOT NULL AUTO_INCREMENT,
    `SiteName` varchar(256) NOT NULL,
    `TentPitches` tinyint(1),
    `TentPitches_Electric` tinyint(1),
    PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

Upvotes: 1

Views: 147

Answers (1)

Pramod Kharade
Pramod Kharade

Reputation: 2085

I am assuming, You will receive the response format as below:

{
    "id": 1,
    "SiteName": "My Site",
    "TentPitches": true
}

Before send response to send method res.send(data) you can modify the response as you are expecting as below:

{
    "SiteName" : "My Site",
    "PitchTypes" : {
        "TentPitches": true
    }
}

You can modify as below:

    const data = {
          "id": 1,
          "SiteName": "My Site",
          "TentPitches": true
      };
     
      let modifyResult={};
      for (const key in data) {
        if (data.hasOwnProperty(key)) {
          if(key==="TentPitches"){
          modifyResult["PitchTypes"]={TentPitches:data[key]};
          }else{
          modifyResult[key] =data[key];
          }
        }
      }

// res.send(modifyResult); Here you can pass the object

it may not be best solution but some what it will give idea around the problem.

Hope, it will solve your problem.

const data = {
          "id": 1,
          "SiteName": "My Site",
          "TentPitches": true
      };
     
      let modifyResult={};
      for (const key in data) {
        if (data.hasOwnProperty(key)) {
          if(key==="TentPitches"){
          modifyResult["PitchTypes"]={TentPitches:data[key]};
          }else{
          modifyResult[key] =data[key];
          }
        }
      }
// res.send(modifyResult); Here you have pass the modify object
console.log("Result is:",modifyResult);

Upvotes: 1

Related Questions