Assuming we have http: HttpClient, I would like to provide a service call wrapper method as follows:
public async post<T>(url: string, body: any): Promise<T> {
// do some stuff
const response = await this.http.post<T>(url, body, this.options).toPromise();
// do more stuff
return response
}
This works as expected for any T except void. The behavior I was hoping for (and am still looking to implement) is to not return any value (Promise<void>) when the server returns no response. I'm now wondering what the best way to implement this is without having a different function for empty response bodies.
I assume there's no way to disambiguate based on the generic type? I tried looking for ways to do that, but it seems there's no way to do it, which makes sense given what TypeScript does and how it works. Fwiw, the type would be available at the call-site (as in, I would be calling that method as service.post<void>(...) in the case I expect an empty response body).
One thing I was wondering is if I could always make it return a string (responseType: "text") and then parse the JSON manually. Then I could check the status and response string, if they were 200 and "" respectively I would know that I can return undefined. If that was the right way to go (and I'm not sure that it is) there are a few questions I have:
- Would manually parsing the JSON have a performance drawback?
- What method should I use to parse it? What does the
HttpClientuse? - How would I make sure that error handling works the same as if it happened from within the
HttpClient.postmethod? Ideally I wouldn't want it to deviate from the error mechanism inside ofHttpClient.post.
Or is there another simple way that I'm missing to implement the desired method? Are any of my assumptions false?
async/awaitfit my mental model very well, I find it easier to think with them compared to observables. It's not set in stone and if it would somehow help with this I wouldn't mind changing it, but as you said it's probably unrelated to my issue.