Is there such a thing as an optional `param`?
mrpickles3rd opened this issue · 3 comments
Hi. I have been using your URL Assembler for some time but now I need a way to have a param optional. at the moment I only need the last one optional but I have a test for it in the middle of a template. Is there a way I can do this now or would this be a new feature?
If it is a new feature how would I get around the query params messing with ?.
test.js
describe('given a template with unused params', function () {
beforeEach(function () {
myUrl = UrlAssembler('/path/:myparam/:notUsed?/:thisIsUsed');
});
describe('.param(key, value)', function () {
it.only('replaces only the used param in the template', function () {
expect(myUrl.param({ myparam: 'hello', thisIsUsed: 'YAY'}).toString()).to.equal('/path/hello/YAY');
})
});
});
Terminal Output:
1) an instance with no baseUrl
given a template with unused params
.param(key, value)
replaces only the used param in the template:
AssertionError: expected '/path/hello/:notUsed?%2F%3AthisIsUsed=&thisIsUsed=YAY' to equal '/path/hello/YAY'
+ expected - actual
-/path/hello/:notUsed?%2F%3AthisIsUsed=&thisIsUsed=YAY
+/path/hello/YAY
at Context.<anonymous> (test/100-instance.js:122:83)
Hello and thank your for your issue. I'm really sorry to only get back to you so late, I haven't find an effective way follow my issues.
At first glance I'd say this looks like an odd use-case. Could you give me a real-world API where this makes sense ?
Not a problem, as you can tell I am also as bad in getting back to things like this.
The use case is like this. I have an image service I use and can not change. most of the time I want to set the size of the image I get. But sometime I want the max size image and to do that I need to remove the size from the URL. I have the URLs in config but with the need to have the full template with no optional params I need to have 2 of everything.
config:
{
images: {
uk: "${UK_URL}/:uuid/:type/:size",
ukBackground: "${UK_URL}/:uuid/:type",
....
This mean I need to have a more complex config.get where it looks something like:
const url = UrlAssembler()
.template(config.get(`images.${country}${(background || '')}`))
. param({ ...ARGS });
...
<img src={url} />
Update:
I have tried to do it for you but the way that UrlAssembler handles unused params and query string had mad it hard for me, I will try again at some point but I need to get v2 to work on.
Alright I see. I also use these services from time to time :)
The problem here is that I use basic string substitution and I have been rather purposefully keeping away from any actual parsing of the template strings.
One thing you could look into could be to Path.normalize() the URL path ?