verifiy json else throw error fetch request

Viewed 39

ExampleObject is an example of what is expected from api endpoint

let ExampleObject={
  "id":"",
  "name":"",
  "Body":""
}

how to make sure that the response has those keys without looping through the response? Response is a json object not an array

function handleError(err) {
  //handling error code based 
  return err
}

export const GetUsers = async({
  user,
  Following
}, Paging) => {

  try {

    const response = await fetch(Apiurl, {
      method: 'GET',
      withCredentials: true,
      credentials: 'include',
      headers: {
        'Authorization': Token,
        'Content-Type': 'application/json'
      }
    })

    if (response.status != 200) {
      throw ('Error Sending request')
    }

    const ResponseArray = await response.json();
    //Verify object here
    if ('Key') {
      throw ('error with json')
    }
    return ResponseArray
    
  } catch (err) {
    throw (handleError(err))
  };
};

and then I call GetUsers from another module

async function callapi() {
  try {
    await GetUsers(Object, Paging)
  } catch (err) {

  }
}
1 Answers

You could use if ("id" in ExampleObject && "name" in ExampleObject && "Body" in ExampleObject) {}

Related