- From: Oliver Joseph Ash <notifications@github.com>
- Date: Sun, 27 Dec 2020 11:09:21 -0800
- To: whatwg/url <url@noreply.github.com>
- Cc: Subscribed <subscribed@noreply.github.com>
- Message-ID: <whatwg/url/issues/354/751504831@github.com>
I am trying to write an immutable wrapper for `URL` because I want to avoid using mutable objects. Unfortunately I believe this is not possible without something like the proposed `URL.from` from above. Instead of overriding a property on a class instance (i.e. mutation), the idea is we can construct a new URL object immutably: ```ts const urlClass = new URL('https://foo.bar/a?b'); const fromClass = (klass) => ({ hash: klass.hash, host: klass.host, hostname: klass.hostname, href: klass.href, password: klass.password, pathname: klass.pathname, port: klass.port, protocol: klass.protocol, origin: klass.origin, searchParams: klass.searchParams, search: klass.search, username: klass.username, }); const urlObject = fromClass(urlClass); // Now we have an object, we can create new objects immutably using spread, // and then override properties as we wish in order to manipulate the URL const newUrlObject = { ...urlObject, pathname: '/c', searchParams: new SearchParams('?d'), }; ``` Now, I want to convert `newUrlObject` back to a `URL` class so I can stringify it back to a URL string ("https://foo.bar/c?d"), e.g. ```ts const result = toClass(newUrlObject).toString(); // "https://foo.bar/c?d" ``` I imagined I could write a function `toClass` that converts my URL object back to a `URL` class. But it seems there is no straightforward way to write this function, without something like the proposed `URL.from`. For now, I'm having to use [Node's legacy `url.format`](https://nodejs.org/dist/latest-v12.x/docs/api/url.html#url_url_format_urlobject) to convert my URL object to a string, but I would like to avoid using this legacy API. --- @domenic In response to the following suggestion of yours: > I suggest people just use the following: > > ```js > Object.assign(new URL("https://example.com/"), { ... pieces go here ... }); > ``` I believe this won't work for some properties which are read only (`origin` and `searchParams`), so I don't think this is a usable solution unfortunately. -- You are receiving this because you are subscribed to this thread. Reply to this email directly or view it on GitHub: https://github.com/whatwg/url/issues/354#issuecomment-751504831
Received on Sunday, 27 December 2020 19:09:33 UTC