badgateway/react-ketting

not able to fetch the POST response status code

sazyadav opened this issue · 5 comments

const post = async (url: string, data: any) => {
const client = ClientAPI.getInstance();
const resource = client.go(url);
const response = await resource.post({ data });
console.log(response);
};

How can I get the status code from above POST request response?

evert commented

Hi @sazyadav ,

One of Ketting's goals is to try and create a library that uses HTTP as intended, but try to make good decisions on its own when receiving certain HTTP statuses. For example, when there's a 4xx or 5xx error it will emit an error (which does expose a status code).

If you're doing something which will potentially create a new resource and emit a 201 status code, what you probably want is postFollow, which can give you a reference to the newly created resource.

So the post function doesn't give you direct access to the status code, but I'm wondering why you would want it

@evert, Thanks for reply !..

I wanna achieve something like :

const post = async (url: string, data: any) => {
const client = ClientAPI.getInstance();
const resource = client.go(url);
const response = await resource.post({ data });
console.log(response);
}

I wanna call above post method:

const response = post(url, data);
if(response.statusCode === 201) return toast('success);
return toast('error')..

could you please suggest me how can I acheive above functionality?

evert commented

All @sazyadav . All 2xx status codes should be treated as successful, so you should be able to simplify your code to this:

try {
   await resource.post({ data });
   // 200, 201, 202 all go here
   return toast('success');
} catch (err) {
  // any 4xx or 5xx code goes here.
  return toast('error');
}

Does that work for you? If not, why not?

Thanks a lot for your quick reply and help @evert .. Really appreciate your time & effort..
above code worked for me..

evert commented

Glad to hear it!