-2

I have the following NodeJs code in my AWS lambda as part of a larger lambda.

It calls an external API to return data regarding tournament schedules, I am able to get the response back from the API but I am unsure how to access the fields in the JSON response that I need.

This is my first time working with JS and NodeJS so I am unfamiliar with this.

const promise = new Promise((resolve, reject) => {
  
  const options = {
  host: 'MY_HOST',
  path: 'MY_PATH',
   headers: {
        'key': 'value'
      }
    }
  
    const req = https.get(options, res => {
      let rawData = '';

      res.on('data', chunk => {
        rawData += chunk;
      });

      res.on('end', () => {
        try {
          resolve(JSON.parse(rawData));
        } catch (err) {
          reject(new Error(err));
        }
      });
    });
    
    req.on('error', err => {
      reject(new Error(err));
    });
  });
  
  // TODO - get promise result and iterate response
  promise.then();

The response return is as follows (only showing first object for simplicity):

    {
  "_id": {
    "$oid": "6346b02601a3c2111621c8e4"
  },
  "orgId": "1",
  "year": "2023",
  "schedule": [
    {
      "tournId": "464",
      "name": "Fortinet Championship",
      "timeZone": "America/Los_Angeles",
      "date": {
        "weekNumber": "37",
        "start": {
          "$date": {
            "$numberLong": "1663200000000"
          }
        },
        "end": {
          "$date": {
            "$numberLong": "1663459200000"
          }
        }
      },
      "format": "stroke",
      "courses": [
        {
          "host": "Yes",
          "location": {
            "state": "CA",
            "city": "Napa",
            "country": "USA"
          },
          "courseName": "Silverado Resort and Spa (North Course)",
          "courseId": "552"
        }
      ],
      "purse": {
        "$numberInt": "8000000"
      },
      "winnersShare": {
        "$numberInt": "1440000"
      },
      "fedexCupPoints": {
        "$numberInt": "500"
      }
    }
  ]
}

The fields that I need access to are:

schedule[0].date.start

schedule[0].date.end

This is because I want to do e.g:

// loop each result and assert if current epoch is in the date Range
  var currentTournamentId;
  
  for(){
      
      if(currentEpoch >= schedule.date.start && currentEpoch <=  schedule.date.end) {
      
        currentTournamentId = currentTournament.getId();
        break;
          
      }
  }

How can I access these fields from the response?

java12399900
  • 1,485
  • 7
  • 26
  • 56

1 Answers1

-1

Install body-parser andrequire it

let schedule = req.body.schedule;

schedule.forEach((item) => {
  let start = item.date.start;
  let end = item.date.end;

  // do something
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
milner236
  • 37
  • 9
  • Your answer could be improved by adding an example of how you install `body-parser` and how you use/define it. – Tyler2P Nov 09 '22 at 17:08