decorateRequests
is the wrong API for this. Its purpose is to add to or surround the behavior of requests already fully formed, not to alter the request itself.
What you are looking for is mutateRequests
, which allows you to change any part of the raw URLRequest
(including the URL itself, which includes the params) before Siesta takes control of it.
Unfortunately, URLRequest
’s Obj-C-era API for working with params is a bit cumbersome — but it can do the job. If you want to add foo=bar
to all requests, and if you want that to work properly whether or not the URL already has HTTP parameters, the safest way to do it is to break the URL into its components, add a new URLQueryItem
for foo=bar
, then reconstruct the URL:
service.configure {
$0.mutateRequests { req in
guard
let url = req.url,
var components = URLComponents(url: url, resolvingAgainstBaseURL: true)
else {
return
}
components.queryItems =
(components.queryItems ?? [])
+ [URLQueryItem(name: "foo", value: "bar")]
req.url = components.url
}
}
Note that this is the correct approach for adding query params globally across a set of resources, overriding their individual logical URLs. It sounds like this is indeed what you’re after.
However, if you (or any others reading this) want instead to create a resource whose URL happens to have query params that are part of what make it unique — the far more common use case — then resource.withParam(…)
is the right thing to use.
There is a subtle difference between these approaches: resource.withParam("foo", "bar")
returns a new resource with a different URL, logically distinct from resource
, that can have different latest data, different requests in progress, etc. On the other hand, the mutateRequests
basically says, “Whatever you think the URL is, I secretly add these extra params when talking to the server — but the extra params do not make it a distinct resource.” Be careful which one you’re using.