Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lib/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()}` : ""}`
);
}

Expand Down
33 changes: 25 additions & 8 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down