jmtellez / CLI-mate

Node CLI app that gives you the weather forecast for a given city.
6 stars 10 forks source link

Cannot read property 'length' of undefined #6

Closed aaronzshey closed 3 years ago

aaronzshey commented 3 years ago
➜  ~ cli-mate mcallen
⠸ Getting geocodes/usr/local/lib/node_modules/@jmt3559/cli-mate/utils/geocode.js:14
      } else if (body.features.length === 0) {
                               ^

TypeError: Cannot read property 'length' of undefined

Possible REST API parse error - I'll try to fix this, but put it out here so others can see it. Edit: no, it was because I don't have a mapbox api key. We should specify that both api keys are required for cli-mate to function.

jmtellez commented 3 years ago

Its on the README.md

aaronzshey commented 3 years ago

Any way to expose the API keys? I just got a mapbox API key, but its still throwing the same error. I can't find the .env file.

jmtellez commented 3 years ago

Make sure you are naming your environment variables exactly as the README says. process.env property returns an object containing the user environment, no need for .env file

aaronzshey commented 3 years ago

Turns out the API keys are contained in ~/.zprofile. I'm re-opening this issue because cli-mate is unfortunately parsing the response JSON wrong - I manually queried the URL with postman and it returned this:

{
    "type": "FeatureCollection",
    "query": [
        "mcallen"
    ],
    "features": [
        {
            "id": "place.9211585200717980",
            "type": "Feature",
            "place_type": [
...

I think I should be able to get the keys with [features] instead of .features - my fork here

Oops, I can't re-open my own issues - @jmtellez do you mind re-opening it?

Edit: I tested my own script:

const request = require("postman-request");

const geocodingURL = `https://api.mapbox.com/geocoding/v5/mapbox.places/mcallen.json?access_token=MY_API_TOKEN`;
request({ url: geocodingURL, json: true }, (err, { body } = {} ) => {
  if (err) console.log(err)
  console.log(body.features.length)
})

> 5

No idea why cli-mate isn't working on my machine.

Second edit: Getting more and more confused here. New error:

          latitude: body.features[0].center[1],
                                 ^
TypeError: Cannot read property '0' of undefined

I think I'll just leave this issue for now and start making the IP thing.

jmtellez commented 3 years ago

Look at the response from your snippet above:

{
    "type": "FeatureCollection",
    "query": [
        "mcallen"
    ],
    "features": [
        {
            "id": "place.9211585200717980",
            "type": "Feature",
            "place_type": [
...

features is a JSON property, so dot notation is correct. Arrays can be values of an object property like features that is why your output is showing 5. we are using the first value in the array as it the most relevant result.