diff --git a/lib/model.ts b/lib/model.ts index bf7aee7..5a3ad7e 100644 --- a/lib/model.ts +++ b/lib/model.ts @@ -381,14 +381,16 @@ export default class Model< url(options = this.urlOptions): string { const base = result(this, "urlRoot", options) || result(this.collection, "url", options) || urlError(); + const { pathname, searchParams } = new URL(base, window.location.origin); if (this.isNew()) { return base; } return ( - base.replace(/[^/]$/, "$&/") + - window.encodeURIComponent(this.get((this.constructor as typeof Model).idAttribute)) + pathname.replace(/[^/]$/, "$&/") + + window.encodeURIComponent(this.get((this.constructor as typeof Model).idAttribute)) + + `${searchParams.toString() ? `?${searchParams.toString()}` : ""}` ); } diff --git a/test/model.test.js b/test/model.test.js index 971d8ab..a89d19e 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -470,19 +470,36 @@ describe("Model", () => { expect(model.url()).toEqual("/library"); }); - it("appends its id to the url if not new", () => { + describe("appends its id to the url if not new", () => { class _Model extends Model { static idAttribute = "name"; } - model = new _Model({ name: "noah?grant" }); - model.urlRoot = () => "/library"; - expect(model.url()).toEqual("/library/noah%3Fgrant"); + beforeEach(() => { + vi.stubGlobal("location", { origin: "https://bobsdonuts.com" }); + }); - collection = new Collection(); - collection.url = () => "/library"; - model = new _Model({ name: "noah?grant" }, { collection }); - expect(model.url()).toEqual("/library/noah%3Fgrant"); + it("when there are no query params", () => { + model = new _Model({ name: "noah?grant" }); + model.urlRoot = () => "/library"; + expect(model.url()).toEqual("/library/noah%3Fgrant"); + + collection = new Collection(); + collection.url = () => "/library"; + model = new _Model({ name: "noah?grant" }, { collection }); + expect(model.url()).toEqual("/library/noah%3Fgrant"); + }); + + it("when there are query params attached to the url", () => { + model = new _Model({ name: "noah?grant" }); + model.urlRoot = () => "/library?foo=bar"; + expect(model.url()).toEqual("/library/noah%3Fgrant?foo=bar"); + + collection = new Collection(); + collection.url = () => "/library?foo=bar"; + model = new _Model({ name: "noah?grant" }, { collection }); + expect(model.url()).toEqual("/library/noah%3Fgrant?foo=bar"); + }); }); it("is called by default with its urlOptions", () => {