Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix non-canonical crate name pages #10369

Merged
merged 2 commits into from
Jan 13, 2025
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
30 changes: 25 additions & 5 deletions app/adapters/crate.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,23 @@ export default class CrateAdapter extends ApplicationAdapter {
coalesceFindRequests = true;

findRecord(store, type, id, snapshot) {
let { include } = snapshot;
// This ensures `crate.versions` are always fetched from another request.
if (include === undefined) {
snapshot.include = 'keywords,categories,downloads';
return super.findRecord(store, type, id, setDefaultInclude(snapshot));
}

queryRecord(store, type, query, adapterOptions) {
return super.queryRecord(store, type, setDefaultInclude(query), adapterOptions);
}

/** Removes the `name` query parameter and turns it into a path parameter instead */
urlForQueryRecord(query) {
let baseUrl = super.urlForQueryRecord(...arguments);
if (!query.name) {
return baseUrl;
}
return super.findRecord(store, type, id, snapshot);

let crateName = query.name;
delete query.name;
return `${baseUrl}/${crateName}`;
}

groupRecordsForFindMany(store, snapshots) {
Expand All @@ -22,3 +33,12 @@ export default class CrateAdapter extends ApplicationAdapter {
return result;
}
}

function setDefaultInclude(query) {
if (query.include === undefined) {
// This ensures `crate.versions` are always fetched from another request.
query.include = 'keywords,categories,downloads';
}

return query;
}
2 changes: 1 addition & 1 deletion app/routes/crate.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default class CrateRoute extends Route {
let crateName = params.crate_id;

try {
return await this.store.findRecord('crate', crateName);
return this.store.peekRecord('crate', crateName) || (await this.store.queryRecord('crate', { name: crateName }));
} catch (error) {
if (error instanceof NotFoundError) {
let title = `${crateName}: Crate not found`;
Expand Down
16 changes: 15 additions & 1 deletion e2e/acceptance/crate.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { test, expect } from '@/e2e/helper';
import { expect, test } from '@/e2e/helper';

test.describe('Acceptance | crate page', { tag: '@acceptance' }, () => {
test('visiting a crate page from the front page', async ({ page, mirage }) => {
Expand Down Expand Up @@ -139,6 +139,20 @@ test.describe('Acceptance | crate page', { tag: '@acceptance' }, () => {
await expect(page.locator('[data-test-try-again]')).toBeVisible();
});

test('works for non-canonical names', async ({ page, mirage }) => {
await mirage.addHook(server => {
let crate = server.create('crate', { name: 'foo-bar' });
server.create('version', { crate });
});

await page.goto('/crates/foo_bar');

await expect(page).toHaveURL('/crates/foo_bar');
await expect(page).toHaveTitle('foo-bar - crates.io: Rust Package Registry');

await expect(page.locator('[data-test-heading] [data-test-crate-name]')).toHaveText('foo-bar');
});

test('navigating to the all versions page', async ({ page, mirage }) => {
await mirage.addHook(server => {
server.loadFixtures();
Expand Down
7 changes: 6 additions & 1 deletion mirage/route-handlers/crates.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { Response } from 'miragejs';
import { getSession } from '../utils/session';
import { compareIsoDates, compareStrings, notFound, pageParams, releaseTracks } from './-utils';

function toCanonicalName(name) {
return name.toLowerCase().replace(/-/g, '_');
}

export function list(schema, request) {
const { start, end } = pageParams(request);

Expand Down Expand Up @@ -56,7 +60,8 @@ export function register(server) {

server.get('/api/v1/crates/:name', function (schema, request) {
let { name } = request.params;
let crate = schema.crates.findBy({ name });
let canonicalName = toCanonicalName(name);
let crate = schema.crates.all().models.find(it => toCanonicalName(it.name) === canonicalName);
if (!crate) return notFound();
let serialized = this.serialize(crate);
let includes = request.queryParams?.include ?? '';
Expand Down
13 changes: 13 additions & 0 deletions tests/acceptance/crate-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,19 @@ module('Acceptance | crate page', function (hooks) {
assert.dom('[data-test-try-again]').exists();
});

test('works for non-canonical names', async function (assert) {
let crate = this.server.create('crate', { name: 'foo-bar' });
this.server.create('version', { crate });

await visit('/crates/foo_bar');

assert.strictEqual(currentURL(), '/crates/foo_bar');
assert.strictEqual(currentRouteName(), 'crate.index');
assert.strictEqual(getPageTitle(), 'foo-bar - crates.io: Rust Package Registry');

assert.dom('[data-test-heading] [data-test-crate-name]').hasText('foo-bar');
});

test('navigating to the all versions page', async function (assert) {
this.server.loadFixtures();

Expand Down
61 changes: 61 additions & 0 deletions tests/mirage/crates/get-by-id-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,67 @@ module('Mirage | GET /api/v1/crates/:id', function (hooks) {
});
});

test('works for non-canonical names', async function (assert) {
let crate = this.server.create('crate', { name: 'foo-bar' });
this.server.create('version', { crate, num: '1.0.0-beta.1' });

let response = await fetch('/api/v1/crates/foo_bar');
assert.strictEqual(response.status, 200);
assert.deepEqual(await response.json(), {
categories: [],
crate: {
badges: [],
categories: [],
created_at: '2010-06-16T21:30:45Z',
default_version: '1.0.0-beta.1',
description: 'This is the description for the crate called "foo-bar"',
documentation: null,
downloads: 0,
homepage: null,
id: 'foo-bar',
keywords: [],
links: {
owner_team: '/api/v1/crates/foo-bar/owner_team',
owner_user: '/api/v1/crates/foo-bar/owner_user',
reverse_dependencies: '/api/v1/crates/foo-bar/reverse_dependencies',
version_downloads: '/api/v1/crates/foo-bar/downloads',
versions: '/api/v1/crates/foo-bar/versions',
},
max_version: '1.0.0-beta.1',
max_stable_version: null,
name: 'foo-bar',
newest_version: '1.0.0-beta.1',
repository: null,
updated_at: '2017-02-24T12:34:56Z',
versions: ['1'],
yanked: false,
},
keywords: [],
versions: [
{
id: '1',
crate: 'foo-bar',
crate_size: 0,
created_at: '2010-06-16T21:30:45Z',
dl_path: '/api/v1/crates/foo-bar/1.0.0-beta.1/download',
downloads: 0,
license: 'MIT/Apache-2.0',
links: {
dependencies: '/api/v1/crates/foo-bar/1.0.0-beta.1/dependencies',
version_downloads: '/api/v1/crates/foo-bar/1.0.0-beta.1/downloads',
},
num: '1.0.0-beta.1',
published_by: null,
readme_path: '/api/v1/crates/foo-bar/1.0.0-beta.1/readme',
rust_version: null,
updated_at: '2017-02-24T12:34:56Z',
yanked: false,
yank_message: null,
},
],
});
});

test('includes related versions', async function (assert) {
let crate = this.server.create('crate', { name: 'rand' });
this.server.create('version', { crate, num: '1.0.0' });
Expand Down
Loading