(RESTFUL api Javascript get function) How to return 0 if account is not found in mapping?

Viewed 46

I have a mapping

"balances": {
  "1": "1000",
  "2": "2000",
  "3": "3000",
}

How do return 0 if the account number cant be found?

my code so far is

app.get('/GetBalanceByAddress/:id', function (req, res) {
        res.end(JSON.stringify(balances.balances[req.params.id], null, 4));
});

for example, right now /GetBalance/1 returns 1000

/GetBalance/2 returns 2000

/GetBalance/3 returns 3000

and /GetBalance/4 returns nothing.

How do i get /GetBalance/(AnyNonExistentAddress) to return 0?

3 Answers

Right, please use try catch or if statement.


app.get('/GetBalanceByAddress/:id', function (req, res) {
  try{
    res.end(JSON.stringify(balances.balances[req.params.id]));
  }
  catch{
    res.end("0");
  } 
});

or

app.get('/GetBalanceByAddress/:id', function (req, res) {
  if (balances.balances[req.params.id]) {
    res.end(JSON.stringify(balances.balances[req.params.id]));
 
  }
  else {
    res.end("0");
  }  
});

If you're using an ES2020 compatible browser, you can use the nullish coalescing operator:

const balances = { "balances": {
  "1": "1000",
  "2": "2000",
  "3": "3000",
}
};

let id = 1;
console.log(balances.balances[id] ?? 0);
id = 4;
console.log(balances.balances[id] ?? 0);

you could wrap in a try/catch block

app.get('/GetBalanceByAddress/:id', function (req, res) {
  try{
    res.end(JSON.stringify(balances.balances[req.params.id], null, 4));
  });
  }
  catch{
    return 0;
  } 
Related