how to optimize this code: different http calls
hi everybody,
i am pretty sure, this code can be optimized to avoid code duplication, so i would be happy to get some ideas from you!
public function call(int $kunde, string $method,string $resource,int $resource_id=0, array $data=[]): Response
{
return match ($method) {
"LIST" => Http::acceptJson()
->timeout(config('exporter.api.timeout'))
->withHeaders(['X-KUNDE' => $kunde])
->withOptions(['debug' => $this->debug])
->withToken(config('exporter.api.token'))
->retry(config('exporter.api.retry.times'), config('exporter.api.retry.sleep'))
->get(config('exporter.api.url').$resource),
"GET" => Http::acceptJson()
->timeout(config('exporter.api.timeout'))
->withHeaders(['X-KUNDE' => $kunde])
->withOptions(['debug' => $this->debug])
->withToken(config('exporter.api.token'))
->retry(config('exporter.api.retry.times'), config('exporter.api.retry.sleep'))
->get(config('exporter.api.url').$resource.'/'.$resource_id),
"ADD" => Http::acceptJson()
->timeout(config('exporter.api.timeout'))
->withHeaders(['X-KUNDE' => $kunde])
->withOptions(['debug' => $this->debug])
->withToken(config('exporter.api.token'))
->retry(config('exporter.api.retry.times'), config('exporter.api.retry.sleep'))
->post(config('exporter.api.url').$resource,$data),
"DELETE" => Http::acceptJson()
->timeout(config('exporter.api.timeout'))
->withHeaders(['X-KUNDE' => $kunde])
->withOptions(['debug' => $this->debug])
->withToken(config('exporter.api.token'))
->retry(config('exporter.api.retry.times'), config('exporter.api.retry.sleep'))
->delete(config('exporter.api.url').$resource.'/'.$resource_id),
};
}
thanks for your ideas!
A very simple approach would be extracting your duplicate code in a distinct method like :
protected function httpClient($kunde)
{
return Http::acceptJson()
->timeout(config('exporter.api.timeout'))
->withHeaders(['X-KUNDE' => $kunde])
->withOptions(['debug' => $this->debug])
->withToken(config('exporter.api.token'))
->retry(config('exporter.api.retry.times'), config('exporter.api.retry.sleep'));
}
public function call(int $kunde, string $method,string $resource,int $resource_id=0, array $data=[]): Response
{
return match ($method) {
"LIST" => $this->httpClient($kunde)
->get(config('exporter.api.url').$resource),
"GET" => $this->httpClient($kunde)
->get(config('exporter.api.url').$resource.'/'.$resource_id),
"ADD" => $this->httpClient($kunde)
->post(config('exporter.api.url').$resource,$data),
"DELETE" => $this->httpClient($kunde)
->delete(config('exporter.api.url').$resource.'/'.$resource_id),
};
}
After that If you need extra flexibility, you could convert that httpClient method to a php Class and add other options and configuration.
Hope it could help
oh boy, the fluent design confused me here 🤦 thanks for this very simple and practical solution 😊👍
Please or to participate in this conversation.