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
7 changes: 7 additions & 0 deletions client/src/api/albumDetail.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@ import { buildSchema, validate } from 'graphql';
import { expect, it } from 'vitest';

import { ALBUM_DETAIL } from './albumDetail.js';
import { DELETE_REVIEW, UPSERT_REVIEW } from './reviews.js';

it('validates the album-detail operation against the repository schema', () => {
expect(validate(buildSchema(schemaSource), ALBUM_DETAIL)).toEqual([]);
});

it('validates review mutations against the repository schema', () => {
const schema = buildSchema(schemaSource);
expect(validate(schema, UPSERT_REVIEW)).toEqual([]);
expect(validate(schema, DELETE_REVIEW)).toEqual([]);
});
6 changes: 6 additions & 0 deletions client/src/api/albumDetail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export type AlbumDetail = {
pageInfo: { hasNextPage: boolean; endCursor: string | null };
totalCount: number;
};
myReview: { id: string; rating: number; comment: string } | null;
};

type AlbumDetailData = { album: AlbumDetail | null };
Expand Down Expand Up @@ -60,6 +61,11 @@ export const ALBUM_DETAIL: TypedDocumentNode<AlbumDetailData, AlbumDetailVariabl
}
averageRating
reviewCount
myReview {
id
rating
comment
}
reviews(first: $reviewFirst, after: $reviewAfter) {
edges {
cursor
Expand Down
10 changes: 7 additions & 3 deletions client/src/api/client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client';
import type { Reference, StoreObject } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

import type { AlbumConnection } from './searchAlbums.js';
import { getUserId } from './userIdentity.js';

// Album nodes are normalized references inside the cache, not query-result objects.
type CachedConnection = Omit<AlbumConnection, 'edges'> & {
Expand Down Expand Up @@ -55,7 +57,9 @@ export const cache = new InMemoryCache({
// ApolloClient coordinates requests and the cache for components under ApolloProvider.
export const apolloClient = new ApolloClient({
cache,
// HttpLink sends GraphQL operations over HTTP, independently of the /project2/ asset base.
// TODO(#6): Verify the endpoint and any identity header against the real backend.
link: new HttpLink({ uri: import.meta.env.VITE_GRAPHQL_URL || '/graphql' }),
// Every request carries the simulated identity. It is not authentication;
// the server uses it only to separate this browser's reviews and crate.
link: setContext((_, { headers }) => ({
headers: { ...headers, 'X-User-Id': getUserId() },
})).concat(new HttpLink({ uri: import.meta.env.VITE_GRAPHQL_URL || '/graphql' })),
});
44 changes: 44 additions & 0 deletions client/src/api/reviews.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { gql } from '@apollo/client';
import type { TypedDocumentNode } from '@apollo/client';

type ReviewPayload = {
review: { id: string; rating: number; comment: string };
album: { id: string };
};

type DeleteReviewPayload = {
deletedReviewId: string;
album: { id: string };
};

export const UPSERT_REVIEW: TypedDocumentNode<
{ upsertReview: ReviewPayload },
{ input: { albumId: string; rating: number; comment: string } }
> = gql`
mutation UpsertReview($input: UpsertReviewInput!) {
upsertReview(input: $input) {
review {
id
rating
comment
}
album {
id
}
}
}
`;

export const DELETE_REVIEW: TypedDocumentNode<
{ deleteReview: DeleteReviewPayload },
{ id: string }
> = gql`
mutation DeleteReview($id: ID!) {
deleteReview(id: $id) {
deletedReviewId
album {
id
}
}
}
`;
47 changes: 47 additions & 0 deletions client/src/api/userIdentity.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { getUserId, USER_ID_STORAGE_KEY } from './userIdentity.js';

const generatedId = '550e8400-e29b-41d4-a716-446655440000';

beforeEach(() => {
window.localStorage.clear();
vi.spyOn(crypto, 'randomUUID').mockReturnValue(generatedId);
});

afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});

describe('getUserId', () => {
it('creates and persists a UUID the first time', () => {
expect(getUserId()).toBe(generatedId);
expect(window.localStorage.getItem(USER_ID_STORAGE_KEY)).toBe(generatedId);
});

it('reuses a stored UUID instead of creating a new user', () => {
window.localStorage.setItem(USER_ID_STORAGE_KEY, generatedId);

expect(getUserId()).toBe(generatedId);
expect(crypto.randomUUID).not.toHaveBeenCalled();
});

it('replaces malformed storage with a UUID', () => {
window.localStorage.setItem(USER_ID_STORAGE_KEY, 'not-a-uuid');

expect(getUserId()).toBe(generatedId);
expect(window.localStorage.getItem(USER_ID_STORAGE_KEY)).toBe(generatedId);
});

it('creates a version 4 UUID when randomUUID is unavailable', () => {
vi.stubGlobal('crypto', {
getRandomValues: (bytes: Uint8Array) => {
bytes.set([...Array(16).keys()]);
return bytes;
},
});

expect(getUserId()).toBe('00010203-0405-4607-8809-0a0b0c0d0e0f');
});
});
31 changes: 31 additions & 0 deletions client/src/api/userIdentity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
export const USER_ID_STORAGE_KEY = 'crate.user-id';

const UUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

function isUuid(value: string | null): value is string {
return value !== null && UUID_PATTERN.test(value);
}

function createUuid(): string {
if (typeof crypto.randomUUID === 'function') return crypto.randomUUID();

const bytes = crypto.getRandomValues(new Uint8Array(16));
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}

/**
* This is a simulated identity, not authentication. It lets the API associate
* a review or crate item with this browser without asking the user to sign in.
*/
export function getUserId(): string {
const existing = window.localStorage.getItem(USER_ID_STORAGE_KEY);
if (isUuid(existing)) return existing.toLowerCase();

const userId = createUuid();
window.localStorage.setItem(USER_ID_STORAGE_KEY, userId);
return userId;
}
47 changes: 47 additions & 0 deletions client/src/components/ReviewForm.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
.review-form {
border-top: 1px solid var(--border);
margin-top: 1.25rem;
padding-top: 1.25rem;
}
.review-form h3 {
font-size: 1rem;
}
.review-form fieldset {
border: 0;
margin: 0 0 1rem;
padding: 0;
}
.review-form legend,
.review-form > label {
display: block;
font-weight: 700;
margin-bottom: 0.4rem;
}
.review-form__ratings {
display: flex;
flex-wrap: wrap;
gap: 0.4rem 0.75rem;
}
.review-form__ratings label {
align-items: center;
display: flex;
gap: 0.25rem;
}
.review-form textarea {
border: 1px solid var(--border);
border-radius: 6px;
display: block;
resize: vertical;
width: 100%;
}
.review-form__actions {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
margin-top: 1rem;
}
.secondary-button {
background: transparent;
border: 1px solid var(--accent);
color: var(--accent);
}
62 changes: 62 additions & 0 deletions client/src/components/ReviewForm.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { MockedProvider } from '@apollo/client/testing/react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { expect, it, vi } from 'vitest';

import { UPSERT_REVIEW } from '../api/reviews.js';
import ReviewForm from './ReviewForm.js';

it('requires an accessible 1 to 5 star choice before it saves', () => {
render(
<MockedProvider>
<ReviewForm albumId="1" review={null} onChanged={vi.fn()} />
</MockedProvider>,
);

fireEvent.click(screen.getByRole('button', { name: 'Publish review' }));
expect(screen.getByRole('alert')).toHaveTextContent(
'Choose a rating from 1 to 5 stars',
);
expect(screen.getAllByRole('radio')).toHaveLength(5);
expect(screen.getByRole('radio', { name: '5 stars' })).not.toBeChecked();
expect(screen.getByRole('textbox', { name: /comment/i })).toHaveAttribute(
'maxlength',
'2000',
);
});

it('saves the selected rating and optional comment', async () => {
const onChanged = vi.fn(() => Promise.resolve(undefined));
render(
<MockedProvider
mocks={[
{
request: {
query: UPSERT_REVIEW,
variables: { input: { albumId: '1', rating: 5, comment: 'A classic.' } },
},
result: {
data: {
upsertReview: {
review: { id: '1', rating: 5, comment: 'A classic.' },
album: { id: '1' },
},
},
},
},
]}
>
<ReviewForm albumId="1" review={null} onChanged={onChanged} />
</MockedProvider>,
);

fireEvent.click(screen.getByRole('radio', { name: '5 stars' }));
fireEvent.change(screen.getByRole('textbox', { name: /comment/i }), {
target: { value: 'A classic.' },
});
fireEvent.click(screen.getByRole('button', { name: 'Publish review' }));

await waitFor(() => expect(onChanged).toHaveBeenCalledOnce());
const status = await screen.findByRole('status');
expect(status).toHaveTextContent('Your review was published.');
expect(status).toHaveFocus();
});
Loading