From 9ffd79ff28dcc75fe360cbf492f723000ee37ab9 Mon Sep 17 00:00:00 2001 From: "hasan.fawzi" Date: Fri, 23 Oct 2026 12:29:44 +0200 Subject: [PATCH 1/6] feat(web): integrate recipes and cookbook with GraphQL --- README.md | 6 +- apps/web/src/App.tsx | 1 + .../recipe/RecipeCard/RecipeCard.tsx | 4 + apps/web/src/features/auth/authApi.ts | 44 +- .../features/cookbook/CookbookPage.test.tsx | 491 +++----------- .../src/features/cookbook/CookbookPage.tsx | 168 +++-- .../features/cookbook/cookbookBrowseState.ts | 9 +- .../cookbook/cookbookUrlState.test.ts | 18 +- .../src/features/cookbook/cookbookUrlState.ts | 2 +- .../cookbook/mockCookbookQuery.test.ts | 5 +- .../features/cookbook/mockCookbookQuery.ts | 11 +- .../features/explore/ExploreControls.test.tsx | 14 +- .../src/features/explore/ExplorePage.test.tsx | 612 ++++-------------- apps/web/src/features/explore/ExplorePage.tsx | 231 ++++--- .../features/explore/SERVER_INTEGRATION.md | 2 + .../explore/exploreBrowseState.test.ts | 6 +- .../features/explore/exploreBrowseState.ts | 10 +- .../features/explore/exploreUrlState.test.ts | 20 +- .../src/features/explore/exploreUrlState.ts | 2 +- .../src/features/explore/mockExploreQuery.ts | 4 +- .../recipe-detail/RecipeDetailPage.test.tsx | 275 +++----- .../recipe-detail/RecipeDetailPage.tsx | 235 +++---- .../recipes/RecipeCreatePage.test.tsx | 199 +++--- .../src/features/recipes/RecipeCreatePage.tsx | 540 +++++++--------- .../features/recipes/RecipeQueryStatus.tsx | 21 + apps/web/src/features/recipes/recipeApi.ts | 92 +++ .../src/features/recipes/useRecipeQuery.ts | 43 ++ apps/web/src/lib/graphqlClient.ts | 68 ++ apps/web/src/store.ts | 55 -- apps/web/src/test/recipeApiFixtures.ts | 58 ++ apps/web/src/types/recipe.ts | 11 +- docs/frontend-integration.md | 47 ++ docs/recipe-api.md | 27 +- e2e/auth-cookie.spec.ts | 17 + e2e/recipe-api.spec.ts | 170 +++++ e2e/smoke.spec.ts | 54 +- 36 files changed, 1656 insertions(+), 1916 deletions(-) create mode 100644 apps/web/src/features/recipes/RecipeQueryStatus.tsx create mode 100644 apps/web/src/features/recipes/recipeApi.ts create mode 100644 apps/web/src/features/recipes/useRecipeQuery.ts create mode 100644 apps/web/src/lib/graphqlClient.ts create mode 100644 apps/web/src/test/recipeApiFixtures.ts create mode 100644 docs/frontend-integration.md create mode 100644 e2e/recipe-api.spec.ts diff --git a/README.md b/README.md index af57e27..e494aef 100644 --- a/README.md +++ b/README.md @@ -112,19 +112,19 @@ Frontend blir tilgjengelig på: http://127.0.0.1:5173/project2/ ``` -Oppskriftsvisningen kan også kjøres med frontend alene: +Frontend-serveren kan også startes separat (API og PostgreSQL kreves for data): ```bash npm run dev:web ``` -Innlogging og registrering krever imidlertid både API-et og PostgreSQL. +Oppskriftsvisning, cookbook og innlogging krever både API-et og PostgreSQL. Se [frontend integration checklist](docs/frontend-integration.md). Ikke legg `.env`, passord, tokens eller andre hemmeligheter i Git. ## Authentication -Registration, login and logout use GraphQL and PostgreSQL. Both the API and database must be running; recipe browsing still uses mock data. Configure DATABASE_URL in .env and run `npm run db:migrate` before starting the API. User and session creation run in one transaction, so a failed session insert rolls back the new user. +Registration, login and logout use GraphQL and PostgreSQL. Both the API and database must be running; recipe browsing and CRUD also use the API. Configure DATABASE_URL in .env and run `npm run db:migrate` before starting the API. User and session creation run in one transaction, so a failed session insert rolls back the new user. Sessions use a host-only HttpOnly cookie (`t31_project2_session`, SameSite=Lax, Path=/, seven-day lifetime). GraphQL context resolves the user from the cookie. Tokens are not returned to frontend JavaScript or stored in localStorage. Logout revokes the server session and clears the cookie. Temporary API failures preserve the cookie for retry. Existing users must log in again after this migration. diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index baf38e4..cd06058 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -31,6 +31,7 @@ export function App() { }> } /> + } /> } /> } /> diff --git a/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx b/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx index 9d7584c..f55e881 100644 --- a/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx +++ b/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx @@ -60,6 +60,7 @@ type RecipeCardBaseProps = Omit< * Save action. */ saved?: boolean; + savePending?: boolean; /** * Enables the built-in Save/Saved action @@ -104,6 +105,7 @@ export default function RecipeCard({ servings, tags = [], saved = false, + savePending = false, onSaveChange, action, className = '', @@ -153,6 +155,8 @@ export default function RecipeCard({ variant="secondary" size="sm" aria-pressed={saved} + disabled={savePending} + aria-busy={savePending} onClick={handleSaveButtonClick} aria-label={ saved diff --git a/apps/web/src/features/auth/authApi.ts b/apps/web/src/features/auth/authApi.ts index 6e8b431..16f4e2e 100644 --- a/apps/web/src/features/auth/authApi.ts +++ b/apps/web/src/features/auth/authApi.ts @@ -1,4 +1,4 @@ -import { print } from 'graphql'; +import { ApiError, graphqlRequest as request } from '../../lib/graphqlClient'; import type { TypedDocumentNode } from '@graphql-typed-document-node/core'; import { RegisterDocument, @@ -7,7 +7,6 @@ import { SignOutDocument, } from '../../../../../contracts/generated'; -const GRAPHQL_URL = import.meta.env.DEV ? '/graphql' : '/project2/api/graphql'; const UNAVAILABLE = 'Authentication is temporarily unavailable. Please try again.'; const errorMessages: Record = { @@ -16,43 +15,22 @@ const errorMessages: Record = { INVALID_INPUT: 'Check the information you entered and try again.', RATE_LIMITED: 'Too many attempts. Please try again in a minute.', }; -interface GraphQLResponse { - data?: T; - errors?: Array<{ extensions?: { code?: string } }>; -} async function graphqlRequest( document: TypedDocumentNode, variables: V, ): Promise { - let response: Response; - try { - response = await fetch(GRAPHQL_URL, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Requested-With': 'recipe-platform', - }, - credentials: 'same-origin', - body: JSON.stringify({ query: print(document), variables }), - }); - } catch { - throw new Error('Unable to connect. Check your connection and try again.'); - } - if (!response.ok) throw new Error(UNAVAILABLE); - let result: GraphQLResponse; try { - const json: unknown = await response.json(); - if (!json || typeof json !== 'object' || Array.isArray(json)) - throw new Error(); - result = json as GraphQLResponse; - } catch { - throw new Error(UNAVAILABLE); + return await request(document, variables); + } catch (error) { + if (error instanceof ApiError) { + throw new Error( + error.code === 'NETWORK_ERROR' + ? error.message + : (errorMessages[error.code] ?? UNAVAILABLE), + ); + } + throw error; } - const error = result.errors?.[0]; - if (error) - throw new Error(errorMessages[error.extensions?.code ?? ''] ?? UNAVAILABLE); - if (!result.data) throw new Error(UNAVAILABLE); - return result.data; } export async function registerUser( name: string, diff --git a/apps/web/src/features/cookbook/CookbookPage.test.tsx b/apps/web/src/features/cookbook/CookbookPage.test.tsx index 3b6348c..0180bb9 100644 --- a/apps/web/src/features/cookbook/CookbookPage.test.tsx +++ b/apps/web/src/features/cookbook/CookbookPage.test.tsx @@ -1,425 +1,96 @@ -import { render, screen, within } from '@testing-library/react'; +import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter, useLocation } from 'react-router-dom'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; - -import { INITIAL_SAVED_RECIPE_IDS, useAppStore } from '../../store'; - +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { + apiPage, + apiRecipe, + apiUser, + mockRecipeFetch, +} from '../../test/recipeApiFixtures'; +import { useAppStore } from '../../store'; import CookbookPage from './CookbookPage'; -const scrollToMock = vi.fn(); - -function LocationProbe() { - const location = useLocation(); - - return
{location.search}
; +function Location() { + return

{useLocation().search}

; } - -function renderCookbookPage(initialEntry = '/cookbook') { - return render( - +function mount(entry = '/cookbook') { + render( + - + , ); } - -describe('CookbookPage', () => { - beforeEach(() => { - scrollToMock.mockClear(); - - useAppStore.setState({ - savedRecipeIds: [...INITIAL_SAVED_RECIPE_IDS], - }); - - Object.defineProperty(window, 'scrollTo', { - value: scrollToMock, - writable: true, - }); +beforeEach(() => + useAppStore.setState({ + currentUser: apiUser, + sessionStatus: 'authenticated', + }), +); +afterEach(() => vi.unstubAllGlobals()); + +it('requests cookbook scopes from the server', async () => { + const variables: unknown[] = []; + mockRecipeFetch((_operation, args) => { + variables.push(args); + return { + data: { + cookbook: apiPage([ + { ...apiRecipe, visibility: 'private', isCreatedByCurrentUser: true }, + ]), + }, + }; }); - - it('shows All by default', () => { - renderCookbookPage(); - - expect( - screen.getByRole('heading', { - name: 'My Cookbook', - }), - ).toBeTruthy(); - - expect( - screen.getByText(/recipes found/i, { - selector: '.cookbook-page__result-count', - }), - ).toBeTruthy(); - - expect( - ( - screen.getByRole('combobox', { - name: 'Recipe source', - }) as HTMLSelectElement - ).value, - ).toBe('all'); - }); - - it('switches to Saved and writes the scope to the URL', async () => { - const user = userEvent.setup(); - - renderCookbookPage(); - - await user.selectOptions( - screen.getByRole('combobox', { - name: 'Recipe source', - }), + mount('/cookbook?view=created'); + expect(await screen.findByRole('heading', { name: 'API soup' })).toBeTruthy(); + expect(variables).toContainEqual( + expect.objectContaining({ scope: 'created' }), + ); + await userEvent + .setup() + .selectOptions( + screen.getByRole('combobox', { name: 'Recipe source' }), 'saved', ); - - expect(screen.getByText('4 recipes found')).toBeTruthy(); - - expect(screen.getByTestId('location-search').textContent).toBe( - '?view=saved', - ); - }); - - it('shows private owned recipes in Created', async () => { - const user = userEvent.setup(); - - renderCookbookPage(); - - await user.selectOptions( - screen.getByRole('combobox', { - name: 'Recipe source', - }), - 'created', - ); - - expect( - screen.getByRole('link', { - name: 'Simple tomato soup', - }), - ).toBeTruthy(); - - expect( - screen.getByRole('link', { - name: 'Slow-cooked lamb and vegetable stew', - }), - ).toBeTruthy(); - }); - - it('searches Cookbook and writes search to the URL', async () => { - const user = userEvent.setup(); - - renderCookbookPage(); - - const searchInput = screen.getByRole('searchbox', { - name: 'Search cookbook recipes', - }); - - await user.type(searchInput, 'lentils'); - - await user.click( - screen.getByRole('button', { - name: 'Search', - }), - ); - - expect(screen.getByText('1 recipe found')).toBeTruthy(); - - expect( - screen.getByRole('link', { - name: 'Red lentil soup', - }), - ).toBeTruthy(); - - expect(screen.getByTestId('location-search').textContent).toBe( - '?q=lentils', - ); - }); - - it('restores scope, filters, and sort from the URL', () => { - renderCookbookPage( - '/cookbook?view=created&category=dinner&sort=alphabetical', - ); - - expect( - ( - screen.getByRole('combobox', { - name: 'Recipe source', - }) as HTMLSelectElement - ).value, - ).toBe('created'); - - expect( - ( - screen.getByRole('combobox', { - name: 'Category', - }) as HTMLSelectElement - ).value, - ).toBe('dinner'); - - expect( - ( - screen.getByRole('combobox', { - name: 'Sort by', - }) as HTMLSelectElement - ).value, - ).toBe('alphabetical'); - }); - - it('does not add Save, Unsave, or Edit actions to cookbook cards', () => { - renderCookbookPage(); - - const firstCard = screen.getAllByRole('article')[0]; - - expect(firstCard).toBeTruthy(); - - if (!firstCard) { - return; + await waitFor(() => + expect(variables).toContainEqual( + expect.objectContaining({ scope: 'saved' }), + ), + ); +}); +it('removes an unsaved recipe and accepts the server-clamped page', async () => { + let saved = true; + mockRecipeFetch((operation) => { + if (operation === 'UnsaveRecipe') { + saved = false; + return { data: { unsaveRecipe: true } }; } - - expect( - within(firstCard).queryByRole('button', { - name: /Save .* to My Cookbook/i, - }), - ).toBeNull(); - - expect( - within(firstCard).queryByRole('button', { - name: /Remove .* from My Cookbook/i, - }), - ).toBeNull(); - - expect( - within(firstCard).queryByRole('button', { - name: /Edit/i, - }), - ).toBeNull(); - }); - - it('shows recipe source choices inside the filter sheet', async () => { - const user = userEvent.setup(); - - renderCookbookPage(); - - await user.click( - screen.getByRole('button', { - name: 'Filters', - hidden: true, - }), - ); - - expect( - screen.getByRole('button', { - name: 'All', - }), - ).toBeTruthy(); - - expect( - screen.getByRole('button', { - name: 'Saved', - }), - ).toBeTruthy(); - - expect( - screen.getByRole('button', { - name: 'Created', - }), - ).toBeTruthy(); - }); - - it('counts a non-default recipe source as an active filter', () => { - renderCookbookPage('/cookbook?view=saved'); - - expect( - screen.getByRole('button', { - name: 'Filters (1)', - hidden: true, - }), - ).toBeTruthy(); - }); - - it('applies mobile filters to the results and URL', async () => { - const user = userEvent.setup(); - - renderCookbookPage(); - - await user.click( - screen.getByRole('button', { - name: 'Filters', - hidden: true, - }), - ); - - await user.click( - screen.getByRole('button', { - name: 'Soup', - }), - ); - - await user.click( - screen.getByRole('button', { - name: '30 min or less', - }), - ); - - await user.click( - screen.getByRole('button', { - name: 'Apply filters', - }), - ); - - expect(screen.getByText('1 recipe found')).toBeTruthy(); - - expect( - screen.getByRole('link', { - name: 'Simple tomato soup', - }), - ).toBeTruthy(); - - expect(screen.getByTestId('location-search').textContent).toBe( - '?category=soup&time=lte30', - ); - }); - - it('discards mobile filter changes when closed without Apply', async () => { - const user = userEvent.setup(); - - renderCookbookPage(); - - await user.click( - screen.getByRole('button', { - name: 'Filters', - hidden: true, - }), - ); - - await user.click( - screen.getByRole('button', { - name: 'Created', - }), - ); - - await user.click( - screen.getByRole('button', { - name: 'Dinner', - }), - ); - - await user.click( - screen.getByRole('button', { - name: 'Close filters', - }), - ); - - expect(screen.getByText('9 recipes found')).toBeTruthy(); - expect(screen.getByTestId('location-search').textContent).toBe(''); - - await user.click( - screen.getByRole('button', { - name: 'Filters', - hidden: true, - }), - ); - - expect( - screen.getByRole('button', { name: 'All' }).getAttribute('aria-pressed'), - ).toBe('true'); - - expect( - screen - .getByRole('button', { name: 'Created' }) - .getAttribute('aria-pressed'), - ).toBe('false'); - - expect( - screen - .getByRole('button', { name: 'All categories' }) - .getAttribute('aria-pressed'), - ).toBe('true'); - - expect( - screen - .getByRole('button', { name: 'Dinner' }) - .getAttribute('aria-pressed'), - ).toBe('false'); - }); - - it('prevents Apply when custom cooking time is invalid', async () => { - const user = userEvent.setup(); - - renderCookbookPage(); - - await user.click( - screen.getByRole('button', { - name: 'Filters', - hidden: true, - }), - ); - - await user.click( - screen.getByRole('button', { - name: 'Custom maximum', - }), - ); - - await user.click( - screen.getByRole('button', { - name: 'Apply filters', - }), - ); - - expect( - screen.getByText('Enter a maximum cooking time before applying filters.'), - ).toBeTruthy(); - - expect(screen.getByText('9 recipes found')).toBeTruthy(); - expect(screen.getByTestId('location-search').textContent).toBe(''); - }); - - it('clears mobile filters and applies the cleared state', async () => { - const user = userEvent.setup(); - - renderCookbookPage('/cookbook?view=created&category=soup&time=lte30'); - - expect(screen.getByText('1 recipe found')).toBeTruthy(); - - expect( - screen.getByRole('link', { - name: 'Simple tomato soup', - }), - ).toBeTruthy(); - - await user.click( - screen.getByRole('button', { - name: 'Filters (3)', - hidden: true, - }), - ); - - await user.click( - screen.getByRole('button', { - name: 'Clear filters', - }), - ); - - expect(screen.getByTestId('location-search').textContent).toBe( - '?view=created&category=soup&time=lte30', - ); - - await user.click( - screen.getByRole('button', { - name: 'Apply filters', - }), - ); - - expect(screen.getByText('9 recipes found')).toBeTruthy(); - expect(screen.getByTestId('location-search').textContent).toBe(''); - - expect( - screen.getByRole('button', { - name: 'Filters', - hidden: true, - }), - ).toBeTruthy(); + return { + data: { + cookbook: apiPage(saved ? [{ ...apiRecipe, isSaved: true }] : []), + }, + }; }); + mount('/cookbook?view=saved&page=99'); + const user = userEvent.setup(); + await waitFor(() => + expect(screen.getByTestId('location').textContent).toBe('?view=saved'), + ); + await user.click( + await screen.findByRole('button', { name: /Remove API soup/i }), + ); + await user.click(screen.getByRole('button', { name: 'Unsave' })); + expect(await screen.findByText('No saved recipes yet')).toBeTruthy(); + expect(screen.getByTestId('location').textContent).toBe('?view=saved'); +}); +it('shows session-expired failures with retry', async () => { + mockRecipeFetch(() => ({ + errors: [{ extensions: { code: 'UNAUTHENTICATED' } }], + })); + mount(); + expect( + await screen.findByText('Your session has expired. Please sign in again.'), + ).toBeTruthy(); + expect(screen.queryByText('Your cookbook is empty')).toBeNull(); }); diff --git a/apps/web/src/features/cookbook/CookbookPage.tsx b/apps/web/src/features/cookbook/CookbookPage.tsx index a6796ad..a704feb 100644 --- a/apps/web/src/features/cookbook/CookbookPage.tsx +++ b/apps/web/src/features/cookbook/CookbookPage.tsx @@ -1,4 +1,11 @@ -import { useEffect, useMemo, useRef, useState, type SubmitEvent } from 'react'; +import { + useCallback, + useEffect, + useMemo, + useRef, + useState, + type SubmitEvent, +} from 'react'; import { useSearchParams } from 'react-router-dom'; import RecipeCard from '../../components/recipe/RecipeCard/RecipeCard'; @@ -13,7 +20,7 @@ import { DEFAULT_RECIPE_FILTER_STATE, RECIPE_PAGE_SIZE, } from '../../lib/recipeBrowse/recipeBrowse'; -import { useAppStore } from '../../store'; +import type { Recipe } from '../../types/recipe'; import CookbookControls from './CookbookControls'; import { @@ -27,7 +34,13 @@ import { readCookbookUrlState, type CookbookUrlState, } from './cookbookUrlState'; -import { getMockCookbookResult } from './mockCookbookQuery'; +import { + listRecipes, + changeRecipeSaved, + recipeErrorMessage, +} from '../recipes/recipeApi'; +import { useRecipeQuery } from '../recipes/useRecipeQuery'; +import RecipeQueryStatus from '../recipes/RecipeQueryStatus'; import './CookbookPage.css'; function CookbookPage() { @@ -35,7 +48,9 @@ function CookbookPage() { const [searchParams, setSearchParams] = useSearchParams(); - const savedRecipeIds = useAppStore((state) => state.savedRecipeIds); + const pendingSaves = useRef(new Set()); + const [savingIds, setSavingIds] = useState([]); + const [saveError, setSaveError] = useState(''); const { scope, search, browseState, page } = useMemo( () => readCookbookUrlState(searchParams), @@ -46,14 +61,33 @@ function CookbookPage() { const queryFilters = getCookbookQueryFilters(browseState); - const result = getMockCookbookResult({ - scope, - search, - savedRecipeIds, - ...queryFilters, + const { category, maxCookingMinutes } = queryFilters; + const load = useCallback( + (signal: AbortSignal) => + listRecipes( + { + search, + category, + maxCookingMinutes, + page, + pageSize: RECIPE_PAGE_SIZE, + }, + scope, + signal, + ), + [search, category, maxCookingMinutes, page, scope], + ); + const query = useRecipeQuery( + JSON.stringify([search, category, maxCookingMinutes, page, scope]), + load, + ); + const result = query.data ?? { + items: [], + totalItems: 0, + pageCount: 0, page, pageSize: RECIPE_PAGE_SIZE, - }); + }; const activeFilterCount = countActiveCookbookFilters(browseState); @@ -70,7 +104,7 @@ function CookbookPage() { * Keep the URL synchronized with that normalized result. */ useEffect(() => { - if (result.page === page) { + if (!query.data || result.page === page) { return; } @@ -85,7 +119,15 @@ function CookbookPage() { replace: true, }, ); - }, [browseState, page, result.page, scope, search, setSearchParams]); + }, [ + query.data, + browseState, + page, + result.page, + scope, + search, + setSearchParams, + ]); function updateUrlState(nextState: CookbookUrlState, replace = false) { setSearchParams(createCookbookSearchParams(nextState), { @@ -188,6 +230,21 @@ function CookbookPage() { }); } + async function handleRecipeSaveChange(recipe: Recipe, saved: boolean) { + if (pendingSaves.current.has(recipe.id)) return; + pendingSaves.current.add(recipe.id); + setSavingIds((ids) => [...ids, recipe.id]); + setSaveError(''); + try { + await changeRecipeSaved(recipe.id, saved); + } catch (error) { + setSaveError(recipeErrorMessage(error)); + } finally { + pendingSaves.current.delete(recipe.id); + setSavingIds((ids) => ids.filter((id) => id !== recipe.id)); + } + } + let emptyStateTitle = 'Your cookbook is empty'; let emptyStateDescription = @@ -261,7 +318,7 @@ function CookbookPage() { type="search" name="search" value={searchInput} - placeholder="Search recipes, ingredients, or tags..." + placeholder="Search recipe titles or descriptions..." autoComplete="off" onChange={(event) => { const value = event.currentTarget.value; @@ -304,42 +361,61 @@ function CookbookPage() { onFiltersChange={handleFiltersChange} /> -

- {result.totalItems} {result.totalItems === 1 ? 'recipe' : 'recipes'}{' '} - found - - {search ? ` for “${search}”` : ''} - - {result.pageCount > 0 - ? `. Page ${result.page} of ${result.pageCount}.` - : '.'} - -

- - {result.totalItems > 0 ? ( + + {saveError &&

{saveError}

} + {!query.loading && !query.error && ( <> -
- {result.items.map((recipe) => ( - - ))} -
- -
- + {result.totalItems}{' '} + {result.totalItems === 1 ? 'recipe' : 'recipes'} found + + {search ? ` for “${search}”` : ''} + + {result.pageCount > 0 + ? `. Page ${result.page} of ${result.pageCount}.` + : '.'} + +

+ + {result.totalItems > 0 ? ( + <> +
+ {result.items.map((recipe) => ( + { + void handleRecipeSaveChange(recipe, saved); + } + : undefined + } + /> + ))} +
+ +
+ +
+ + ) : ( + -
+ )} - ) : ( - )} diff --git a/apps/web/src/features/cookbook/cookbookBrowseState.ts b/apps/web/src/features/cookbook/cookbookBrowseState.ts index 725ab93..19a3dda 100644 --- a/apps/web/src/features/cookbook/cookbookBrowseState.ts +++ b/apps/web/src/features/cookbook/cookbookBrowseState.ts @@ -15,11 +15,8 @@ export const COOKBOOK_SCOPE_OPTIONS = [ export type CookbookScope = (typeof COOKBOOK_SCOPE_OPTIONS)[number]['value']; export const COOKBOOK_SORT_OPTIONS = [ - { value: 'recently-updated', label: 'Recently updated' }, - { value: 'cooking-time', label: 'Cooking time' }, - { value: 'alphabetical', label: 'A–Z' }, + { value: 'newest', label: 'Newest first' }, ] as const; - export type CookbookSort = (typeof COOKBOOK_SORT_OPTIONS)[number]['value']; export type CookbookBrowseState = RecipeFilterState & { @@ -32,7 +29,7 @@ export type CookbookQueryFilters = RecipeQueryFilters & { export const DEFAULT_COOKBOOK_BROWSE_STATE: CookbookBrowseState = { ...DEFAULT_RECIPE_FILTER_STATE, - sort: 'recently-updated', + sort: 'newest', }; export function isCookbookScope(value: string | null): value is CookbookScope { @@ -59,6 +56,6 @@ export function countActiveCookbookFilters(state: CookbookBrowseState) { export function getCookbookSortLabel(sort: CookbookSort) { return ( COOKBOOK_SORT_OPTIONS.find((option) => option.value === sort)?.label ?? - 'Recently updated' + 'Newest first' ); } diff --git a/apps/web/src/features/cookbook/cookbookUrlState.test.ts b/apps/web/src/features/cookbook/cookbookUrlState.test.ts index 2f077ec..a1897f4 100644 --- a/apps/web/src/features/cookbook/cookbookUrlState.test.ts +++ b/apps/web/src/features/cookbook/cookbookUrlState.test.ts @@ -7,6 +7,12 @@ import { } from './cookbookUrlState'; describe('Cookbook URL state', () => { + it('falls back to newest for legacy sort links', () => { + expect( + readCookbookUrlState(new URLSearchParams('sort=recently-updated')) + .browseState.sort, + ).toBe('newest'); + }); it('uses default state for an empty URL', () => { expect(readCookbookUrlState(new URLSearchParams())).toEqual({ scope: 'all', @@ -19,7 +25,7 @@ describe('Cookbook URL state', () => { it('reads scope, search, filters, sort, and page', () => { const state = readCookbookUrlState( new URLSearchParams( - 'view=saved&q=soup&category=dinner&time=lte60&sort=cooking-time&page=2', + 'view=saved&q=soup&category=dinner&time=lte60&page=2', ), ); @@ -30,7 +36,7 @@ describe('Cookbook URL state', () => { category: 'dinner', cookingTime: 'lte60', customMaxMinutes: null, - sort: 'cooking-time', + sort: 'newest', }, page: 2, }); @@ -55,13 +61,13 @@ describe('Cookbook URL state', () => { category: 'dessert', cookingTime: 'custom', customMaxMinutes: 75, - sort: 'alphabetical', + sort: 'newest', }, page: 2, }); expect(params.toString()).toBe( - 'view=created&q=cake&category=dessert&time=custom&maxTime=75&sort=alphabetical&page=2', + 'view=created&q=cake&category=dessert&time=custom&maxTime=75&page=2', ); }); @@ -73,7 +79,7 @@ describe('Cookbook URL state', () => { category: 'soup', cookingTime: 'lte60', customMaxMinutes: null, - sort: 'cooking-time', + sort: 'newest', }, page: 2, }); @@ -85,7 +91,7 @@ describe('Cookbook URL state', () => { category: 'soup', cookingTime: 'lte60', customMaxMinutes: null, - sort: 'cooking-time', + sort: 'newest', }, page: 2, }); diff --git a/apps/web/src/features/cookbook/cookbookUrlState.ts b/apps/web/src/features/cookbook/cookbookUrlState.ts index 3078b9d..59026a8 100644 --- a/apps/web/src/features/cookbook/cookbookUrlState.ts +++ b/apps/web/src/features/cookbook/cookbookUrlState.ts @@ -104,7 +104,7 @@ export function createCookbookSearchParams({ } } - if (browseState.sort !== 'recently-updated') { + if (browseState.sort !== DEFAULT_COOKBOOK_BROWSE_STATE.sort) { searchParams.set('sort', browseState.sort); } diff --git a/apps/web/src/features/cookbook/mockCookbookQuery.test.ts b/apps/web/src/features/cookbook/mockCookbookQuery.test.ts index 123eaa3..b6fa507 100644 --- a/apps/web/src/features/cookbook/mockCookbookQuery.test.ts +++ b/apps/web/src/features/cookbook/mockCookbookQuery.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest'; -import { INITIAL_SAVED_RECIPE_IDS } from '../../store'; +import { recipes } from '../../data/recipes'; +const INITIAL_SAVED_RECIPE_IDS = recipes + .filter((recipe) => recipe.isSaved) + .map((recipe) => recipe.id); import { getMockCookbookResult, type CookbookQuery } from './mockCookbookQuery'; diff --git a/apps/web/src/features/cookbook/mockCookbookQuery.ts b/apps/web/src/features/cookbook/mockCookbookQuery.ts index 2a3d823..1de2226 100644 --- a/apps/web/src/features/cookbook/mockCookbookQuery.ts +++ b/apps/web/src/features/cookbook/mockCookbookQuery.ts @@ -7,7 +7,13 @@ import { } from '../../lib/recipeBrowse/recipeBrowse'; import type { Recipe } from '../../types/recipe'; -import type { CookbookScope, CookbookSort } from './cookbookBrowseState'; +import type { CookbookScope } from './cookbookBrowseState'; + +type CookbookSort = + | 'newest' + | 'recently-updated' + | 'cooking-time' + | 'alphabetical'; export type CookbookQuery = RecipeQueryFilters & { scope: CookbookScope; @@ -52,6 +58,9 @@ function compareAlphabetical(a: Recipe, b: Recipe) { const sortComparators: Record number> = { + newest: (a, b) => + Date.parse(b.createdAt) - Date.parse(a.createdAt) || + b.id.localeCompare(a.id), 'recently-updated': compareRecentlyUpdated, 'cooking-time': compareCookingTime, alphabetical: compareAlphabetical, diff --git a/apps/web/src/features/explore/ExploreControls.test.tsx b/apps/web/src/features/explore/ExploreControls.test.tsx index 0f24033..7c6faff 100644 --- a/apps/web/src/features/explore/ExploreControls.test.tsx +++ b/apps/web/src/features/explore/ExploreControls.test.tsx @@ -18,7 +18,7 @@ function ExploreControlsHarness() { } describe('ExploreControls', () => { - it('uses Trending as the default sort and keeps desktop and mobile state in sync', async () => { + it('uses Newest first as the default sort and keeps desktop and mobile state in sync', async () => { const user = userEvent.setup(); render(); @@ -35,11 +35,11 @@ describe('ExploreControls', () => { name: 'Sort by', }) as HTMLSelectElement; - expect(sort.value).toBe('trending'); + expect(sort.value).toBe('newest'); expect( screen.getByRole('button', { - name: 'Sort: Trending', + name: 'Sort: Newest first', hidden: true, }), ).toBeTruthy(); @@ -199,14 +199,14 @@ describe('ExploreControls', () => { fireEvent.click( screen.getByRole('button', { - name: 'Sort: Trending', + name: 'Sort: Newest first', hidden: true, }), ); await user.click( screen.getByRole('radio', { - name: 'Most saved', + name: 'Newest first', }), ); @@ -218,7 +218,7 @@ describe('ExploreControls', () => { expect( screen.getByRole('button', { - name: 'Sort: Most saved', + name: 'Sort: Newest first', hidden: true, }), ).toBeTruthy(); @@ -229,6 +229,6 @@ describe('ExploreControls', () => { name: 'Sort by', }) as HTMLSelectElement ).value, - ).toBe('most-saved'); + ).toBe('newest'); }); }); diff --git a/apps/web/src/features/explore/ExplorePage.test.tsx b/apps/web/src/features/explore/ExplorePage.test.tsx index 493cb2b..3210682 100644 --- a/apps/web/src/features/explore/ExplorePage.test.tsx +++ b/apps/web/src/features/explore/ExplorePage.test.tsx @@ -1,496 +1,166 @@ -import { render, screen, waitFor, within } from '@testing-library/react'; +import { act, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; - -import { mockUser } from '../../data/users'; -import { INITIAL_SAVED_RECIPE_IDS, useAppStore } from '../../store'; - +import { MemoryRouter, useLocation } from 'react-router-dom'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + apiPage, + apiRecipe, + apiUser, + mockRecipeFetch, +} from '../../test/recipeApiFixtures'; +import { useAppStore } from '../../store'; import ExplorePage from './ExplorePage'; -const scrollToMock = vi.fn(); - -function LocationProbe() { - const location = useLocation(); - - return
{location.search}
; -} - -function HistoryBackButton() { - const navigate = useNavigate(); - - return ( - - ); +function Location() { + return

{useLocation().search}

; } - -function renderExplorePage(initialEntry = '/') { - return render( - +function mount(entry = '/') { + render( + - - + , ); } - -describe('ExplorePage', () => { - beforeEach(() => { - scrollToMock.mockClear(); - - useAppStore.setState({ - search: '', - currentUser: null, - savedRecipeIds: [...INITIAL_SAVED_RECIPE_IDS], - }); - - Object.defineProperty(window, 'scrollTo', { - value: scrollToMock, - writable: true, - }); - }); - - it('renders the default Trending result set', () => { - renderExplorePage(); - - expect( - screen.getByRole('heading', { - name: 'Explore Recipes', - }), - ).toBeTruthy(); - - expect(screen.getByText('4 recipes found')).toBeTruthy(); - - expect(screen.getAllByRole('article')).toHaveLength(4); - }); - - it('searches the catalog and writes committed search to the URL', async () => { - const user = userEvent.setup(); - - renderExplorePage(); - - const searchInput = screen.getByRole('searchbox', { - name: 'Search recipes', - }); - - await user.type(searchInput, 'thai'); - - await user.click( - screen.getByRole('button', { - name: 'Search', - }), - ); - - expect( - screen.getByRole('link', { - name: 'Thai green curry', - }), +beforeEach(() => { + useAppStore.setState({ currentUser: null, sessionStatus: 'anonymous' }); + vi.stubGlobal('scrollTo', vi.fn()); +}); +afterEach(() => vi.unstubAllGlobals()); + +describe('Explore API integration', () => { + it('sends URL filters and pagination to the API', async () => { + const fetch = mockRecipeFetch(() => ({ + data: { + recipes: apiPage([apiRecipe], { + page: 2, + totalPages: 2, + totalCount: 7, + }), + }, + })); + mount('/?q=soup&category=soup&time=lte30&page=2'); + expect( + await screen.findByRole('heading', { name: 'API soup' }), ).toBeTruthy(); - - expect(screen.getByText('1 recipe found')).toBeTruthy(); - - expect(screen.getByTestId('location-search').textContent).toBe('?q=thai'); - }); - - it('applies filters, resets page, and writes them to the URL', async () => { - const user = userEvent.setup(); - - renderExplorePage('/?sort=popular&page=2'); - - await user.selectOptions( - screen.getByRole('combobox', { - name: 'Category', - }), - 'dinner', - ); - - expect(screen.getByRole('status').textContent).toMatch(/recipes found/i); - - expect(screen.getByTestId('location-search').textContent).toBe( - '?category=dinner&sort=popular', - ); - - await user.selectOptions( - screen.getByRole('combobox', { - name: 'Cooking time', - }), - 'lte30', - ); - - expect(screen.getByText('1 recipe found')).toBeTruthy(); - - expect(screen.getByTestId('location-search').textContent).toBe( - '?category=dinner&time=lte30&sort=popular', - ); - }); - - it('restores search, filters, and sorting from the URL', () => { - renderExplorePage('/?q=salmon&category=dinner&time=lte30&sort=popular'); - - expect( - ( - screen.getByRole('searchbox', { - name: 'Search recipes', - }) as HTMLInputElement - ).value, - ).toBe('salmon'); - - expect( - ( - screen.getByRole('combobox', { - name: 'Category', - }) as HTMLSelectElement - ).value, - ).toBe('dinner'); - - expect( - ( - screen.getByRole('combobox', { - name: 'Cooking time', - }) as HTMLSelectElement - ).value, - ).toBe('lte30'); - - expect( - ( - screen.getByRole('combobox', { - name: 'Sort by', - }) as HTMLSelectElement - ).value, - ).toBe('popular'); - - expect( - screen.getByRole('link', { - name: 'Creamy salmon pasta', - }), + const request = JSON.parse(fetch.mock.calls[0]![1].body as string); + expect(request.variables.input).toEqual({ + search: 'soup', + category: 'soup', + maxCookingMinutes: 30, + page: 2, + pageSize: 6, + }); + expect(fetch.mock.calls[0]![1].credentials).toBe('same-origin'); + expect(screen.getByText('7 recipes found')).toBeTruthy(); + expect( + screen.getByRole('option', { name: 'Sort by: Newest first' }), ).toBeTruthy(); + expect(screen.queryByRole('option', { name: 'Trending' })).toBeNull(); }); - - it('changes page while preserving the browse context', async () => { + it('commits search to the URL and resets the requested page', async () => { + const requests: unknown[] = []; + mockRecipeFetch((_operation, variables) => { + requests.push(variables); + return { data: { recipes: apiPage() } }; + }); + mount(); + await screen.findByText('1 recipe found'); const user = userEvent.setup(); - - renderExplorePage('/?sort=popular'); - - await user.click( - screen.getByRole('button', { - name: 'Go to page 2', - }), - ); - - const currentPageButton = screen.getByRole('button', { - name: 'Page 2, current page', - }); - - expect(currentPageButton.getAttribute('aria-current')).toBe('page'); - - expect(screen.getByTestId('location-search').textContent).toBe( - '?sort=popular&page=2', - ); - - expect(scrollToMock).toHaveBeenCalledWith({ - top: 0, - left: 0, - behavior: 'auto', - }); + await user.type(screen.getByRole('searchbox'), 'soup'); + await user.click(screen.getByRole('button', { name: 'Search' })); + await waitFor(() => + expect(requests).toContainEqual({ + input: { + search: 'soup', + category: null, + maxCookingMinutes: null, + page: 1, + pageSize: 6, + }, + }), + ); + expect(screen.getByTestId('location').textContent).toBe('?q=soup'); }); - - it('clamps an out-of-range page and corrects the URL', async () => { - renderExplorePage('/?sort=popular&page=99'); - - await waitFor(() => { - expect(screen.getByTestId('location-search').textContent).toBe( - '?sort=popular&page=2', - ); - }); - - expect( - screen - .getByRole('button', { - name: 'Page 2, current page', - }) - .getAttribute('aria-current'), - ).toBe('page'); - }); - - it('clears a submitted search when the search field is emptied', async () => { - const user = userEvent.setup(); - - renderExplorePage('/?sort=popular'); - - const searchInput = screen.getByRole('searchbox', { - name: 'Search recipes', - }); - - await user.type(searchInput, 'SALMON'); - - await user.click( - screen.getByRole('button', { - name: 'Search', - }), - ); - - expect(screen.getByText('1 recipe found')).toBeTruthy(); - - await user.clear(searchInput); - - expect(screen.getByRole('status').textContent).toMatch(/recipes found/i); - - expect(screen.getByTestId('location-search').textContent).toBe( - '?sort=popular', - ); - }); - - it('clears no-result search and filter criteria while preserving sort', async () => { - const user = userEvent.setup(); - - renderExplorePage('/?category=dinner&sort=popular'); - - const searchInput = screen.getByRole('searchbox', { - name: 'Search recipes', - }); - - await user.type(searchInput, 'definitely-not-a-recipe'); - - await user.click( - screen.getByRole('button', { - name: 'Search', - }), - ); - - expect(screen.getByText(/No recipes found for/i)).toBeTruthy(); - - await user.click( - screen.getByRole('button', { - name: 'Clear search and filters', - }), - ); - - expect(screen.getByRole('status').textContent).toMatch(/recipes found/i); - - expect(screen.getByTestId('location-search').textContent).toBe( - '?sort=popular', - ); - - await waitFor(() => { - expect(document.activeElement).toBe(searchInput); - }); - }); - - it('restores the previous browse state when navigating back', async () => { - const user = userEvent.setup(); - - renderExplorePage(); - - await user.selectOptions( - screen.getByRole('combobox', { - name: 'Sort by', - }), - 'popular', - ); - - await user.selectOptions( - screen.getByRole('combobox', { - name: 'Category', - }), - 'dinner', - ); - - expect(screen.getByTestId('location-search').textContent).toBe( - '?category=dinner&sort=popular', - ); - - await user.click( - screen.getByRole('button', { - name: 'Test browser back', - }), - ); - - await waitFor(() => { - expect( - ( - screen.getByRole('combobox', { - name: 'Category', - }) as HTMLSelectElement - ).value, - ).toBe('all'); - }); - - expect( - ( - screen.getByRole('combobox', { - name: 'Sort by', - }) as HTMLSelectElement - ).value, - ).toBe('popular'); - - expect(screen.getByTestId('location-search').textContent).toBe( - '?sort=popular', - ); - }); - - it('saves an eligible recipe and updates shared state', async () => { - const user = userEvent.setup(); - + it('retains saved state on failure and refetches after success', async () => { useAppStore.setState({ - currentUser: mockUser, - }); - - renderExplorePage('/?q=thai&sort=popular'); - - const recipeLink = screen.getByRole('link', { - name: 'Thai green curry', - }); - - const recipeCard = recipeLink.closest('article'); - - expect(recipeCard).not.toBeNull(); - - if (!recipeCard) { - return; - } - - expect( - within(recipeCard).getByRole('button', { - name: /^Save .* to My Cookbook$/, - }), - ).toBeTruthy(); - - await user.click( - within(recipeCard).getByRole('button', { - name: /^Save .* to My Cookbook$/, - }), - ); - - expect( - within(recipeCard).getByRole('button', { - name: /^Remove .* from My Cookbook$/, - }), - ).toBeTruthy(); - - expect(useAppStore.getState().savedRecipeIds).toContain('thai-green-curry'); - - expect(screen.getByText('Recipe saved')).toBeTruthy(); - - expect( - screen.getByText('“Thai green curry” was saved to My Cookbook.'), - ).toBeTruthy(); - }); - - it('confirms before removing a saved recipe', async () => { + currentUser: apiUser, + sessionStatus: 'authenticated', + }); + let fail = true, + saved = false; + mockRecipeFetch((operation) => { + if (operation === 'SaveRecipe') { + if (fail) return { errors: [{ extensions: { code: 'FORBIDDEN' } }] }; + saved = true; + return { data: { saveRecipe: { ...apiRecipe, isSaved: true } } }; + } + return { data: { recipes: apiPage([{ ...apiRecipe, isSaved: saved }]) } }; + }); + mount(); const user = userEvent.setup(); - - useAppStore.setState({ - currentUser: mockUser, - }); - - renderExplorePage('/?q=falafel&sort=popular'); - - const recipeLink = screen.getByRole('link', { - name: 'Falafel bowl with hummus', - }); - - const recipeCard = recipeLink.closest('article'); - - expect(recipeCard).not.toBeNull(); - - if (!recipeCard) { - return; - } - - expect( - within(recipeCard).getByRole('button', { - name: /^Remove .* from My Cookbook$/, - }), - ).toBeTruthy(); - await user.click( - within(recipeCard).getByRole('button', { - name: /^Remove .* from My Cookbook$/, - }), + await screen.findByRole('button', { name: /Save API soup/i }), ); - expect( - screen.getByRole('dialog', { - name: 'Remove saved recipe?', - }), - ).toBeTruthy(); - - await user.click( - screen.getByRole('button', { - name: 'Unsave', - }), - ); - - expect( - within(recipeCard).getByRole('button', { - name: /^Save .* to My Cookbook$/, - }), + await screen.findByText( + 'You do not have permission to perform this action.', + ), ).toBeTruthy(); - - expect(useAppStore.getState().savedRecipeIds).not.toContain('falafel-bowl'); - - expect(screen.getByText('Recipe removed')).toBeTruthy(); - }); - - it('does not expose Save for recipes created by the current user', () => { - useAppStore.setState({ - currentUser: mockUser, - }); - - renderExplorePage('/?q=apple&sort=popular'); - - const recipeLink = screen.getByRole('link', { - name: 'Norwegian apple cake', - }); - - const recipeCard = recipeLink.closest('article'); - - expect(recipeCard).not.toBeNull(); - - if (!recipeCard) { - return; - } - expect( - within(recipeCard).queryByRole('button', { - name: /^Save .* to My Cookbook$/, - }), + screen.queryByRole('button', { name: /Remove API soup/i }), ).toBeNull(); - + fail = false; + await user.click(screen.getByRole('button', { name: /Save API soup/i })); expect( - within(recipeCard).queryByRole('button', { - name: /^Remove .* from My Cookbook$/, - }), - ).toBeNull(); + await screen.findByRole('button', { name: /Remove API soup/i }), + ).toBeTruthy(); }); - - it('does not expose Save actions while logged out', () => { - renderExplorePage('/?q=thai&sort=popular'); - - const recipeLink = screen.getByRole('link', { - name: 'Thai green curry', - }); - - const recipeCard = recipeLink.closest('article'); - - expect(recipeCard).not.toBeNull(); - - if (!recipeCard) { - return; - } - - expect( - within(recipeCard).queryByRole('button', { - name: /^Save .* to My Cookbook$/, - }), - ).toBeNull(); - - expect( - within(recipeCard).queryByRole('button', { - name: /^Remove .* from My Cookbook$/, - }), - ).toBeNull(); + it('shows errors separately from empty results and supports retry', async () => { + let fail = true; + mockRecipeFetch(() => + fail + ? { errors: [{ extensions: { code: 'API_ERROR' } }] } + : { data: { recipes: apiPage([]) } }, + ); + mount(); + expect(await screen.findByRole('alert')).toBeTruthy(); + expect(screen.queryByText('No recipes available')).toBeNull(); + fail = false; + await userEvent + .setup() + .click(screen.getByRole('button', { name: 'Try again' })); + expect(await screen.findByText('No recipes available')).toBeTruthy(); + }); + it('ignores stale responses after the signed-in user changes', async () => { + let resolve!: (value: unknown) => void; + mockRecipeFetch( + () => + new Promise((done) => { + resolve = done; + }), + ); + mount(); + const oldResolve = resolve; + act(() => + useAppStore.setState({ + currentUser: apiUser, + sessionStatus: 'authenticated', + }), + ); + await act(async () => { + oldResolve({ + data: { + recipes: apiPage([{ ...apiRecipe, title: 'Old user result' }]), + }, + }); + }); + expect(screen.queryByText('Old user result')).toBeNull(); + await act(async () => { + resolve({ data: { recipes: apiPage() } }); + }); + expect( + await screen.findByRole('heading', { name: 'API soup' }), + ).toBeTruthy(); }); }); diff --git a/apps/web/src/features/explore/ExplorePage.tsx b/apps/web/src/features/explore/ExplorePage.tsx index e4b00ce..3d52501 100644 --- a/apps/web/src/features/explore/ExplorePage.tsx +++ b/apps/web/src/features/explore/ExplorePage.tsx @@ -1,4 +1,11 @@ -import { useEffect, useMemo, useRef, useState, type SubmitEvent } from 'react'; +import { + useCallback, + useEffect, + useMemo, + useRef, + useState, + type SubmitEvent, +} from 'react'; import { useSearchParams } from 'react-router-dom'; import RecipeCard from '../../components/recipe/RecipeCard/RecipeCard'; @@ -25,7 +32,13 @@ import { readExploreUrlState, type ExploreUrlState, } from './exploreUrlState'; -import { getMockExploreResult } from './mockExploreQuery'; +import { + listRecipes, + changeRecipeSaved, + recipeErrorMessage, +} from '../recipes/recipeApi'; +import { useRecipeQuery } from '../recipes/useRecipeQuery'; +import RecipeQueryStatus from '../recipes/RecipeQueryStatus'; import './ExplorePage.css'; type SaveFeedback = { @@ -41,9 +54,8 @@ function ExplorePage() { const currentUser = useAppStore((state) => state.currentUser); - const savedRecipeIds = useAppStore((state) => state.savedRecipeIds); - - const setRecipeSaved = useAppStore((state) => state.setRecipeSaved); + const pendingSaves = useRef(new Set()); + const [savingIds, setSavingIds] = useState([]); const [saveFeedback, setSaveFeedback] = useState(null); @@ -62,12 +74,33 @@ function ExplorePage() { const queryFilters = getExploreQueryFilters(browseState); - const result = getMockExploreResult({ - search, - ...queryFilters, + const { category, maxCookingMinutes } = queryFilters; + const load = useCallback( + (signal: AbortSignal) => + listRecipes( + { + search, + category, + maxCookingMinutes, + page, + pageSize: RECIPE_PAGE_SIZE, + }, + undefined, + signal, + ), + [search, category, maxCookingMinutes, page], + ); + const query = useRecipeQuery( + JSON.stringify([search, category, maxCookingMinutes, page]), + load, + ); + const result = query.data ?? { + items: [], + totalItems: 0, + pageCount: 0, page, pageSize: RECIPE_PAGE_SIZE, - }); + }; const activeFilterCount = countActiveExploreFilters(browseState); @@ -90,7 +123,7 @@ function ExplorePage() { * URL page with the normalized page returned by the query. */ useEffect(() => { - if (result.page === page) { + if (!query.data || result.page === page) { return; } @@ -104,7 +137,7 @@ function ExplorePage() { replace: true, }, ); - }, [browseState, page, result.page, search, setSearchParams]); + }, [query.data, browseState, page, result.page, search, setSearchParams]); function updateUrlState(nextState: ExploreUrlState, replace = false) { setSearchParams(createExploreSearchParams(nextState), { @@ -175,22 +208,36 @@ function ExplorePage() { }); } - function handleRecipeSaveChange(recipe: Recipe, saved: boolean) { - setRecipeSaved(recipe.id, saved); - - setSaveFeedback( - saved - ? { - tone: 'success', - title: 'Recipe saved', - message: `“${recipe.title}” was saved to My Cookbook.`, - } - : { - tone: 'info', - title: 'Recipe removed', - message: `“${recipe.title}” was removed from My Cookbook.`, - }, - ); + async function handleRecipeSaveChange(recipe: Recipe, saved: boolean) { + if (pendingSaves.current.has(recipe.id)) return; + pendingSaves.current.add(recipe.id); + setSavingIds((ids) => [...ids, recipe.id]); + try { + await changeRecipeSaved(recipe.id, saved); + + setSaveFeedback( + saved + ? { + tone: 'success', + title: 'Recipe saved', + message: `“${recipe.title}” was saved to My Cookbook.`, + } + : { + tone: 'info', + title: 'Recipe removed', + message: `“${recipe.title}” was removed from My Cookbook.`, + }, + ); + } catch (error) { + setSaveFeedback({ + tone: 'error', + title: 'Unable to update cookbook', + message: recipeErrorMessage(error), + }); + } finally { + pendingSaves.current.delete(recipe.id); + setSavingIds((ids) => ids.filter((id) => id !== recipe.id)); + } } let emptyStateTitle = 'No recipes available'; @@ -199,8 +246,6 @@ function ExplorePage() { emptyStateTitle = `No recipes found for “${search}”`; } else if (hasActiveFilters) { emptyStateTitle = 'No recipes found with these filters'; - } else if (browseState.sort === 'trending') { - emptyStateTitle = 'No trending recipes available'; } let emptyStateDescription = 'There are no public recipes to show right now.'; @@ -208,9 +253,6 @@ function ExplorePage() { if (hasSearchOrFilters) { emptyStateDescription = 'Try changing your search or filters, or clear them to see more recipes.'; - } else if (browseState.sort === 'trending') { - emptyStateDescription = - 'Try another sort option to browse the full recipe catalog.'; } let clearActionLabel = 'Clear filters'; @@ -244,7 +286,7 @@ function ExplorePage() { type="search" name="search" value={searchInput} - placeholder="Search recipes, ingredients, or tags..." + placeholder="Search recipe titles or descriptions..." autoComplete="off" onChange={(event) => { const value = event.currentTarget.value; @@ -283,67 +325,76 @@ function ExplorePage() { onChange={handleBrowseStateChange} /> -

- {result.totalItems} {result.totalItems === 1 ? 'recipe' : 'recipes'}{' '} - found - - {search ? ` for “${search}”` : ''} - - {result.pageCount > 0 - ? `. Page ${result.page} of ${result.pageCount}.` - : '.'} - -

- - {result.totalItems > 0 ? ( + + {!query.loading && !query.error && ( <> -
- {result.items.map((recipe) => { - const saved = savedRecipeIds.includes(recipe.id); - - const canSave = - currentUser !== null && - recipe.visibility === 'public' && - !recipe.isCreatedByCurrentUser; - - return ( - - handleRecipeSaveChange(recipe, nextSaved) - : undefined - } +

+ {result.totalItems}{' '} + {result.totalItems === 1 ? 'recipe' : 'recipes'} found + + {search ? ` for “${search}”` : ''} + + {result.pageCount > 0 + ? `. Page ${result.page} of ${result.pageCount}.` + : '.'} + +

+ + {result.totalItems > 0 ? ( + <> +
+ {result.items.map((recipe) => { + const saved = recipe.isSaved; + + const canSave = + currentUser !== null && + recipe.visibility === 'public' && + !recipe.isCreatedByCurrentUser; + + return ( + + handleRecipeSaveChange(recipe, nextSaved) + : undefined + } + /> + ); + })} +
+ +
+ - ); - })} -
- -
- + + ) : ( + + {clearActionLabel} + + ) : undefined + } /> -
+ )} - ) : ( - - {clearActionLabel} - - ) : undefined - } - /> )} diff --git a/apps/web/src/features/explore/SERVER_INTEGRATION.md b/apps/web/src/features/explore/SERVER_INTEGRATION.md index 1c9e533..0a769f4 100644 --- a/apps/web/src/features/explore/SERVER_INTEGRATION.md +++ b/apps/web/src/features/explore/SERVER_INTEGRATION.md @@ -1,3 +1,5 @@ +> Historical design notes: Explore now uses the GraphQL API. See [the current integration checklist](../../../../../docs/frontend-integration.md) for implemented behavior and remaining work. The mock-query examples below describe the earlier prototype. + # Explore server integration The current Explore implementation uses local mock data, but the feature is structured so the UI can later be connected to a GraphQL/API backend without redesigning the page. diff --git a/apps/web/src/features/explore/exploreBrowseState.test.ts b/apps/web/src/features/explore/exploreBrowseState.test.ts index 09d5710..e70ad05 100644 --- a/apps/web/src/features/explore/exploreBrowseState.test.ts +++ b/apps/web/src/features/explore/exploreBrowseState.test.ts @@ -25,7 +25,7 @@ describe('getExploreQueryFilters', () => { ).toEqual({ category: null, maxCookingMinutes, - sort: 'trending', + sort: 'newest', }); }, ); @@ -36,12 +36,12 @@ describe('getExploreQueryFilters', () => { category: 'dinner', cookingTime: 'custom', customMaxMinutes: 45, - sort: 'most-saved', + sort: 'newest', }), ).toEqual({ category: 'dinner', maxCookingMinutes: 45, - sort: 'most-saved', + sort: 'newest', }); }); }); diff --git a/apps/web/src/features/explore/exploreBrowseState.ts b/apps/web/src/features/explore/exploreBrowseState.ts index 28cea75..113d17e 100644 --- a/apps/web/src/features/explore/exploreBrowseState.ts +++ b/apps/web/src/features/explore/exploreBrowseState.ts @@ -19,12 +19,8 @@ export const EXPLORE_COOKING_TIME_OPTIONS = RECIPE_COOKING_TIME_OPTIONS; export type ExploreCookingTime = RecipeCookingTime; export const EXPLORE_SORT_OPTIONS = [ - { value: 'trending', label: 'Trending' }, - { value: 'popular', label: 'Most popular' }, - { value: 'newest', label: 'Newest' }, - { value: 'most-saved', label: 'Most saved' }, + { value: 'newest', label: 'Newest first' }, ] as const; - export type ExploreSort = (typeof EXPLORE_SORT_OPTIONS)[number]['value']; export type ExploreFilterState = RecipeFilterState; @@ -43,7 +39,7 @@ export const DEFAULT_EXPLORE_FILTER_STATE: ExploreFilterState = { export const DEFAULT_EXPLORE_BROWSE_STATE: ExploreBrowseState = { ...DEFAULT_EXPLORE_FILTER_STATE, - sort: 'trending', + sort: 'newest', }; export function isExploreCategory( @@ -78,6 +74,6 @@ export function countActiveExploreFilters(state: ExploreFilterState) { export function getExploreSortLabel(sort: ExploreSort) { return ( EXPLORE_SORT_OPTIONS.find((option) => option.value === sort)?.label ?? - 'Trending' + 'Newest first' ); } diff --git a/apps/web/src/features/explore/exploreUrlState.test.ts b/apps/web/src/features/explore/exploreUrlState.test.ts index 5f35837..366e66d 100644 --- a/apps/web/src/features/explore/exploreUrlState.test.ts +++ b/apps/web/src/features/explore/exploreUrlState.test.ts @@ -7,6 +7,12 @@ import { } from './exploreUrlState'; describe('Explore URL state', () => { + it('falls back to newest for legacy sort links', () => { + expect( + readExploreUrlState(new URLSearchParams('sort=trending')).browseState + .sort, + ).toBe('newest'); + }); it('uses the default browse state for an empty URL', () => { expect(readExploreUrlState(new URLSearchParams())).toEqual({ search: '', @@ -17,9 +23,7 @@ describe('Explore URL state', () => { it('parses search, category, cooking time, sort, and page', () => { const state = readExploreUrlState( - new URLSearchParams( - 'q=pasta&category=dinner&time=lte30&sort=popular&page=2', - ), + new URLSearchParams('q=pasta&category=dinner&time=lte30&page=2'), ); expect(state).toEqual({ @@ -29,7 +33,7 @@ describe('Explore URL state', () => { category: 'dinner', cookingTime: 'lte30', customMaxMinutes: null, - sort: 'popular', + sort: 'newest', }, page: 2, @@ -45,7 +49,7 @@ describe('Explore URL state', () => { category: 'all', cookingTime: 'custom', customMaxMinutes: 45, - sort: 'trending', + sort: 'newest', }); }); @@ -88,14 +92,14 @@ describe('Explore URL state', () => { category: 'dinner', cookingTime: 'custom', customMaxMinutes: 50, - sort: 'most-saved', + sort: 'newest', }, page: 3, }); expect(params.toString()).toBe( - 'q=curry&category=dinner&time=custom&maxTime=50&sort=most-saved&page=3', + 'q=curry&category=dinner&time=custom&maxTime=50&page=3', ); expect(readExploreUrlState(params)).toEqual({ @@ -105,7 +109,7 @@ describe('Explore URL state', () => { category: 'dinner', cookingTime: 'custom', customMaxMinutes: 50, - sort: 'most-saved', + sort: 'newest', }, page: 3, diff --git a/apps/web/src/features/explore/exploreUrlState.ts b/apps/web/src/features/explore/exploreUrlState.ts index e43f2e7..c76d85a 100644 --- a/apps/web/src/features/explore/exploreUrlState.ts +++ b/apps/web/src/features/explore/exploreUrlState.ts @@ -88,7 +88,7 @@ export function createExploreSearchParams({ } } - if (browseState.sort !== 'trending') { + if (browseState.sort !== DEFAULT_EXPLORE_BROWSE_STATE.sort) { searchParams.set('sort', browseState.sort); } diff --git a/apps/web/src/features/explore/mockExploreQuery.ts b/apps/web/src/features/explore/mockExploreQuery.ts index 23b6b57..0c0bc24 100644 --- a/apps/web/src/features/explore/mockExploreQuery.ts +++ b/apps/web/src/features/explore/mockExploreQuery.ts @@ -3,7 +3,9 @@ import { paginate, type PageResult } from '../../lib/pagination/paginate'; import { filterRecipesByBrowseCriteria } from '../../lib/recipeBrowse/recipeBrowse'; import type { Recipe } from '../../types/recipe'; -import type { ExploreCategory, ExploreSort } from './exploreBrowseState'; +import type { ExploreCategory } from './exploreBrowseState'; + +type ExploreSort = 'trending' | 'popular' | 'newest' | 'most-saved'; export type ExploreQuery = { search: string; diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx index 68a2a1b..945de33 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx @@ -1,206 +1,97 @@ -import '@testing-library/jest-dom/vitest'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; -import { beforeEach, describe, expect, it } from 'vitest'; - -import { INITIAL_SAVED_RECIPE_IDS, useAppStore } from '../../store'; - +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { + apiRecipe, + apiUser, + mockRecipeFetch, +} from '../../test/recipeApiFixtures'; +import { useAppStore } from '../../store'; import RecipeDetailPage from './RecipeDetailPage'; -function LocationProbe() { - const location = useLocation(); - - return ( - - {`${location.pathname}${location.search}`} - - ); -} - -function renderRecipeDetail( - initialEntry: - | string - | { - pathname: string; - state?: unknown; - }, -) { - return render( - +function mount() { + render( + } /> - } /> + Cookbook destination} /> , ); } - -describe('RecipeDetailPage', () => { - beforeEach(() => { - useAppStore.setState({ - savedRecipeIds: [...INITIAL_SAVED_RECIPE_IDS], - userRatings: {}, - }); - }); - - it('shows public non-owner recipe actions and total cooking time', () => { - renderRecipeDetail('/recipes/salmon-pasta'); - - expect( - screen.getByRole('heading', { name: 'Creamy salmon pasta' }), - ).toBeInTheDocument(); - - expect(screen.getByText('30 min')).toBeInTheDocument(); - - expect( - screen.getByRole('button', { name: 'Save to Cookbook' }), - ).toBeInTheDocument(); - - expect( - screen.getByRole('button', { name: 'Rate Recipe' }), - ).toBeInTheDocument(); - }); - - it('scales ingredient amounts when servings change', async () => { - const user = userEvent.setup(); - - renderRecipeDetail('/recipes/salmon-pasta'); - - expect(screen.getByText('400 g')).toBeInTheDocument(); - - const increaseServingButtons = screen.getAllByRole('button', { - name: 'Increase servings', - }); - - expect(increaseServingButtons.length).toBeGreaterThan(0); - - await user.click(increaseServingButtons[0]!); - - expect(screen.getByText('500 g')).toBeInTheDocument(); - - expect(screen.getAllByText('5 servings').length).toBeGreaterThan(0); - }); - - it('saves a recipe into shared cookbook state', async () => { - const user = userEvent.setup(); - - renderRecipeDetail('/recipes/salmon-pasta'); - - await user.click( - screen.getByRole('button', { - name: 'Save to Cookbook', - }), - ); - - expect(useAppStore.getState().savedRecipeIds).toContain('salmon-pasta'); - - expect(screen.getByRole('button', { name: 'Saved' })).toHaveAttribute( - 'aria-pressed', - 'true', - ); - }); - - it('stores a mock user rating and allows it to be changed later', async () => { - const user = userEvent.setup(); - - renderRecipeDetail('/recipes/salmon-pasta'); - - await user.click( - screen.getByRole('button', { - name: 'Rate Recipe', - }), - ); - - await user.click( - screen.getByRole('radio', { - name: '5 stars', - }), - ); - - await user.click( - screen.getByRole('button', { - name: 'Save rating', - }), - ); - - expect(useAppStore.getState().userRatings['salmon-pasta']).toBe(5); - - expect( - screen.getByRole('button', { - name: 'Change rating, currently 5 out of 5', - }), - ).toBeInTheDocument(); - }); - - it('shows owner controls and hides ratings for a private recipe', () => { - renderRecipeDetail('/recipes/tomato-soup'); - - expect(screen.getByText('Private')).toBeInTheDocument(); - - expect( - screen.getByRole('link', { - name: 'Edit Recipe', - }), - ).toBeInTheDocument(); - - expect(screen.queryByRole('img', { name: /out of 5/ })).toBeNull(); - - expect( - screen.queryByRole('button', { - name: 'Rate Recipe', - }), - ).toBeNull(); - - expect( - screen.queryByRole('button', { - name: 'Save to Cookbook', - }), - ).toBeNull(); - }); - - it('returns to the exact source URL stored by recipe navigation', async () => { - const user = userEvent.setup(); - - renderRecipeDetail({ - pathname: '/recipes/salmon-pasta', - state: { - from: '/?q=pasta&category=dinner&page=2', - }, - }); - - await user.click( - screen.getByRole('button', { - name: 'Back to Explore', - }), - ); - - expect(screen.getByTestId('location')).toHaveTextContent( - '/?q=pasta&category=dinner&page=2', - ); - }); - - it('uses the cookbook fallback for an owner recipe opened directly', async () => { - const user = userEvent.setup(); - - renderRecipeDetail('/recipes/lentil-soup'); - - await user.click( - screen.getByRole('button', { - name: 'Back to My Cookbook', - }), - ); - - expect(screen.getByTestId('location')).toHaveTextContent('/cookbook'); +beforeEach(() => + useAppStore.setState({ + currentUser: apiUser, + sessionStatus: 'authenticated', + }), +); +afterEach(() => vi.unstubAllGlobals()); + +it('loads details and scales ingredient quantities without changing the server', async () => { + mockRecipeFetch(() => ({ data: { recipe: apiRecipe } })); + mount(); + expect(await screen.findByRole('heading', { name: 'API soup' })).toBeTruthy(); + expect(screen.getByText('Boil the water.')).toBeTruthy(); + expect(screen.getByText('1 l')).toBeTruthy(); + await userEvent + .setup() + .click(screen.getAllByRole('button', { name: 'Increase servings' })[0]!); + expect(screen.getByText('1.5 l')).toBeTruthy(); + expect(screen.queryByRole('button', { name: 'Rate Recipe' })).toBeNull(); + expect(screen.getByText('Rating recipes is not available yet.')).toBeTruthy(); +}); +it('treats inaccessible private recipes as unavailable', async () => { + mockRecipeFetch(() => ({ data: { recipe: null } })); + mount(); + expect( + await screen.findByRole('heading', { name: 'Recipe not found' }), + ).toBeTruthy(); +}); +it('offers owner editing and deletes only after confirmation', async () => { + const operations: string[] = []; + mockRecipeFetch((operation) => { + operations.push(operation); + return { + data: + operation === 'DeleteRecipe' + ? { deleteRecipe: true } + : { recipe: { ...apiRecipe, isCreatedByCurrentUser: true } }, + }; }); + mount(); + const edit = await screen.findByRole('link', { name: 'Edit Recipe' }); + expect(edit.getAttribute('href')).toBe('/recipes/' + apiRecipe.id + '/edit'); + const user = userEvent.setup(); + await user.click(screen.getByRole('button', { name: 'Delete Recipe' })); + expect(operations).not.toContain('DeleteRecipe'); + await user.click(screen.getByRole('button', { name: 'Delete recipe' })); + expect( + await screen.findByRole('heading', { name: 'Cookbook destination' }), + ).toBeTruthy(); + expect(operations).toContain('DeleteRecipe'); +}); +it('does not offer save actions to anonymous visitors', async () => { + useAppStore.setState({ currentUser: null, sessionStatus: 'anonymous' }); + mockRecipeFetch(() => ({ data: { recipe: apiRecipe } })); + mount(); + await screen.findByRole('heading', { name: 'API soup' }); + expect(screen.queryByRole('button', { name: 'Save to Cookbook' })).toBeNull(); +}); - it('shows a simple not-found state for an unknown recipe id', () => { - renderRecipeDetail('/recipes/does-not-exist'); - - expect( - screen.getByRole('heading', { - name: 'Recipe not found', - }), - ).toBeInTheDocument(); +it('handles malformed recipe IDs as not found without an API request', async () => { + const fetch = mockRecipeFetch(() => { + throw new Error('Must not request an invalid ID'); }); + render( + + + } /> + + , + ); + expect( + await screen.findByRole('heading', { name: 'Recipe not found' }), + ).toBeTruthy(); + expect(fetch).not.toHaveBeenCalled(); }); diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx index 062632d..bdc8bd8 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx @@ -1,22 +1,19 @@ -import { useMemo, useState } from 'react'; +import { useCallback, useRef, useState } from 'react'; import { useLocation, useNavigate, useParams } from 'react-router-dom'; import fallbackRecipeImage from '../../assets/recipe-fallback.png'; import RecipeMeta from '../../components/recipe/RecipeMeta/RecipeMeta'; import RecipeRating from '../../components/recipe/RecipeRating/RecipeRating'; -import RecipeRatingInput from '../../components/recipe/RecipeRatingInput/RecipeRatingInput'; import Avatar from '../../components/ui/Avatar/Avatar'; import Button from '../../components/ui/Button/Button'; import ConfirmationDialog from '../../components/ui/ConfirmationDialog/ConfirmationDialog'; -import Dialog from '../../components/ui/Dialog/Dialog'; import EmptyState from '../../components/ui/EmptyState/EmptyState'; import { Icon } from '../../components/ui/Icon/Icon'; import IconButton from '../../components/ui/IconButton/IconButton'; import LinkButton from '../../components/ui/LinkButton/LinkButton'; import Tag from '../../components/ui/Tag/Tag'; import Toast, { type ToastTone } from '../../components/ui/Toast/Toast'; -import { recipes } from '../../data/recipes'; import { BookmarkIcon, EditIcon, @@ -24,11 +21,18 @@ import { PlusIcon, } from '../../icons/actions'; import { BackIcon } from '../../icons/navigation'; -import { StarIcon } from '../../icons/rating'; import { EmptyStateIcon, PrivateIcon } from '../../icons/recipe'; import { useAppStore } from '../../store'; import type { Recipe } from '../../types/recipe'; +import { + changeRecipeSaved, + deleteRecipe, + getRecipe, + recipeErrorMessage, +} from '../recipes/recipeApi'; +import { useRecipeQuery } from '../recipes/useRecipeQuery'; +import RecipeQueryStatus from '../recipes/RecipeQueryStatus'; import './RecipeDetailPage.css'; const MIN_SERVINGS = 1; @@ -78,21 +82,6 @@ function formatScaledAmount( return String(Math.round(scaledAmount * 100) / 100); } -function getDisplayedRating(recipe: Recipe, userRating?: number) { - if (!userRating) { - return recipe.rating; - } - - const nextCount = recipe.rating.count + 1; - const nextAverage = - (recipe.rating.average * recipe.rating.count + userRating) / nextCount; - - return { - average: Number(nextAverage.toFixed(1)), - count: nextCount, - }; -} - function getSourcePath(locationState: unknown) { const state = locationState as RecipeDetailLocationState | null; @@ -105,27 +94,20 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { const navigate = useNavigate(); const location = useLocation(); - const savedRecipeIds = useAppStore((state) => state.savedRecipeIds); - const setRecipeSaved = useAppStore((state) => state.setRecipeSaved); - const userRatings = useAppStore((state) => state.userRatings); - const setUserRating = useAppStore((state) => state.setUserRating); - const removeUserRating = useAppStore((state) => state.removeUserRating); - + const currentUser = useAppStore((state) => state.currentUser); + const busyRef = useRef(false); + const [busy, setBusy] = useState(false); + const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false); const [selectedServings, setSelectedServings] = useState(recipe.servings); const [confirmUnsaveOpen, setConfirmUnsaveOpen] = useState(false); - const [ratingDialogOpen, setRatingDialogOpen] = useState(false); - const [pendingRating, setPendingRating] = useState(0); const [feedback, setFeedback] = useState(null); const [showAllTags, setShowAllTags] = useState(false); - // TODO(server-auth): replace this mock ownership flag with the authenticated - // user's recipe ownership/authorization returned by the backend. const isOwner = recipe.isCreatedByCurrentUser; const isPrivate = recipe.visibility === 'private'; - const isSaved = savedRecipeIds.includes(recipe.id); - const canSaveOrRate = !isOwner && !isPrivate; - const userRating = userRatings[recipe.id]; - const displayedRating = getDisplayedRating(recipe, userRating); + const isSaved = recipe.isSaved; + const canSaveOrRate = currentUser !== null && !isOwner && !isPrivate; + const displayedRating = recipe.rating; const totalMinutes = recipe.prepMinutes + recipe.cookMinutes; const visibleTags = recipe.tags.filter( @@ -180,63 +162,47 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { }); } + async function performAction(action: () => Promise, message: string) { + if (busyRef.current) return; + busyRef.current = true; + setBusy(true); + try { + await action(); + setFeedback({ tone: 'success', title: 'Recipe updated', message }); + } catch (error) { + setFeedback({ + tone: 'error', + title: 'Unable to update recipe', + message: recipeErrorMessage(error), + }); + } finally { + busyRef.current = false; + setBusy(false); + } + } function handleSaveClick() { if (isSaved) { setConfirmUnsaveOpen(true); return; } - - setRecipeSaved(recipe.id, true); - - setFeedback({ - tone: 'success', - title: 'Recipe saved', - message: `${recipe.title} was added to My Cookbook.`, - }); + void performAction( + () => changeRecipeSaved(recipe.id, true), + 'Recipe saved to My Cookbook.', + ); } - function handleConfirmUnsave() { setConfirmUnsaveOpen(false); - - setRecipeSaved(recipe.id, false); - - setFeedback({ - tone: 'info', - title: 'Recipe removed', - message: `${recipe.title} was removed from My Cookbook.`, - }); - } - - function handleOpenRating() { - setPendingRating(userRating ?? 0); - setRatingDialogOpen(true); - } - - function handleSubmitRating() { - if (pendingRating < 1 || pendingRating > 5) { - return; - } - - setUserRating(recipe.id, pendingRating); - setRatingDialogOpen(false); - - setFeedback({ - tone: 'success', - title: userRating ? 'Rating updated' : 'Rating saved', - message: `You rated ${recipe.title} ${pendingRating} out of 5.`, - }); + void performAction( + () => changeRecipeSaved(recipe.id, false), + 'Recipe removed from My Cookbook.', + ); } - - function handleRemoveRating() { - removeUserRating(recipe.id); - setRatingDialogOpen(false); - setPendingRating(0); - - setFeedback({ - tone: 'info', - title: 'Rating removed', - message: `Your rating for ${recipe.title} was removed.`, - }); + function handleDelete() { + setConfirmDeleteOpen(false); + void performAction(async () => { + await deleteRecipe(recipe.id); + navigate('/cookbook', { replace: true }); + }, 'Recipe deleted.'); } return ( @@ -366,15 +332,23 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
{isOwner ? ( - - + <> + + + + ) : canSaveOrRate ? ( <> +

Rating recipes is not available yet.

) : null}
@@ -607,48 +565,20 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { > You can save this recipe again later. - - setRatingDialogOpen(false)} - footer={ - <> - {userRating ? ( - - ) : null} - - - - - - } - > - - ) : null} + setConfirmDeleteOpen(false)} + > + This action cannot be undone. + {feedback ? (
recipes.find((candidate) => candidate.id === id), + const load = useCallback( + (signal: AbortSignal) => getRecipe(id ?? '', signal), [id], ); + const query = useRecipeQuery(id ?? '', load); + if (query.loading || query.error) return ; + const recipe = query.data; if (!recipe) { return ( @@ -679,7 +612,7 @@ function RecipeDetailPage() { Back to Explore} /> diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx index efbbb31..17f021b 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -1,13 +1,31 @@ import '@testing-library/jest-dom/vitest'; import { fireEvent, render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import RecipeCreatePage from './RecipeCreatePage'; +import { MemoryRouter, Routes, Route } from 'react-router-dom'; +import { apiRecipe, mockRecipeFetch } from '../../test/recipeApiFixtures'; + +function mount(entry = '/recipes/new') { + return render( + + + } /> + } /> + Saved recipe destination} + /> + + , + ); +} +afterEach(() => vi.unstubAllGlobals()); describe('RecipeCreatePage', () => { it('exposes the recipe fields through accessible labels', () => { - render(); + mount(); expect( screen.getByRole('heading', { name: 'Add Recipe' }), @@ -21,13 +39,15 @@ describe('RecipeCreatePage', () => { expect( screen.getByRole('group', { name: /Visibility/ }), ).toBeInTheDocument(); - expect(screen.getByLabelText(/Recipe image/)).toBeInTheDocument(); + expect(screen.queryByLabelText(/Recipe image/)).not.toBeInTheDocument(); + expect(screen.getByLabelText(/Preparation time/)).toBeInTheDocument(); + expect(screen.getByLabelText(/Difficulty/)).toBeInTheDocument(); }); it('shows inline errors and focuses the first invalid field', async () => { const user = userEvent.setup(); - render(); + mount(); fireEvent.change(screen.getByLabelText('Ingredient 1 unit'), { target: { value: '' }, }); @@ -35,12 +55,11 @@ describe('RecipeCreatePage', () => { expect(screen.getByText('Enter a recipe title.')).toBeInTheDocument(); expect( - screen.getByText('Enter a cooking time of at least 1 minute.'), + screen.getByText('Enter cooking minutes from 0 to 10080.'), ).toBeInTheDocument(); expect(screen.getByText('Choose a recipe category.')).toBeInTheDocument(); expect(screen.getByText('Enter an ingredient name.')).toBeInTheDocument(); expect(screen.getByText('Enter a positive amount.')).toBeInTheDocument(); - expect(screen.getByText('Choose an ingredient unit.')).toBeInTheDocument(); expect(screen.getByLabelText('Ingredient 1')).toHaveAttribute( 'aria-invalid', 'true', @@ -49,10 +68,6 @@ describe('RecipeCreatePage', () => { 'aria-invalid', 'true', ); - expect(screen.getByLabelText('Ingredient 1 unit')).toHaveAttribute( - 'aria-invalid', - 'true', - ); expect(screen.getByText('Add an instruction.')).toBeInTheDocument(); expect(screen.getByLabelText(/Recipe title/)).toHaveAttribute( 'aria-invalid', @@ -63,7 +78,7 @@ describe('RecipeCreatePage', () => { it('adds and removes ingredient and instruction rows', async () => { const user = userEvent.setup(); - render(); + mount(); await user.click(screen.getByRole('button', { name: 'Add ingredient' })); expect(screen.getByLabelText('Ingredient 2')).toBeInTheDocument(); @@ -83,7 +98,7 @@ describe('RecipeCreatePage', () => { it('supports structured ingredients and button-based reordering', async () => { const user = userEvent.setup(); - render(); + mount(); await user.type(screen.getByLabelText('Ingredient 1'), 'Flour'); await user.type(screen.getByLabelText('Ingredient 1 amount'), '200'); @@ -139,7 +154,7 @@ describe('RecipeCreatePage', () => { it('reorders ingredients and instructions by drag and drop', async () => { const user = userEvent.setup(); - render(); + mount(); await user.click(screen.getByRole('button', { name: 'Add ingredient' })); await user.type(screen.getByLabelText('Ingredient 1'), 'Flour'); @@ -189,84 +204,92 @@ describe('RecipeCreatePage', () => { expect(screen.getByLabelText('Step 1')).toHaveValue('Bake'); expect(screen.getByLabelText('Step 2')).toHaveValue('Mix'); }); +}); - it('reports an invalid image without sending it anywhere', () => { - render(); - fireEvent.change(screen.getByLabelText(/Recipe image/), { - target: { - files: [ - new File(['not an image'], 'recipe.gif', { type: 'image/gif' }), - ], - }, - }); - - expect( - screen.getByText('Choose a JPG, PNG, or WebP image.'), - ).toBeInTheDocument(); - expect(screen.getByLabelText(/Recipe image/)).toHaveAttribute( - 'aria-invalid', - 'true', - ); +async function fillRecipe() { + const user = userEvent.setup(); + await user.type(screen.getByLabelText(/Recipe title/), 'New soup'); + await user.type(screen.getByLabelText(/Preparation time/), '5'); + await user.type(screen.getByLabelText(/Cooking time/), '0'); + await user.selectOptions(screen.getByLabelText(/Difficulty/), 'medium'); + await user.type(screen.getByLabelText(/Servings/), '2'); + await user.selectOptions(screen.getByLabelText(/Category/), 'soup'); + await user.type(screen.getByLabelText('Ingredient 1'), 'Water'); + await user.type(screen.getByLabelText('Ingredient 1 amount'), '1'); + await user.selectOptions(screen.getByLabelText('Ingredient 1 unit'), 'l'); + await user.type(screen.getByLabelText('Step 1'), 'Mix.'); + return user; +} +it('creates a recipe with explicit times and difficulty, then opens its detail route', async () => { + let input: unknown; + mockRecipeFetch((_operation, variables) => { + input = variables.input; + return { data: { createRecipe: apiRecipe } }; }); - - it('supports dropping, previewing, and removing an image', async () => { - vi.stubGlobal('URL', { - createObjectURL: vi.fn(() => 'blob:recipe-preview'), - revokeObjectURL: vi.fn(), - }); - - try { - const user = userEvent.setup(); - render(); - const imageFile = new File(['image data'], 'recipe.png', { - type: 'image/png', - }); - const imageSelector = screen - .getByText('Choose a recipe image') - .closest('label'); - - fireEvent.drop(imageSelector!, { - dataTransfer: { files: [imageFile] }, - }); - - expect(screen.getByRole('dialog')).toHaveTextContent('Crop recipe image'); - expect( - screen.queryByRole('img', { - name: 'Selected recipe', - }), - ).not.toBeInTheDocument(); - - await user.click(screen.getByRole('button', { name: 'Cancel' })); - - expect(screen.getByText('Choose a recipe image')).toBeInTheDocument(); - expect( - screen.queryByRole('img', { - name: 'Selected recipe', - }), - ).not.toBeInTheDocument(); - } finally { - vi.unstubAllGlobals(); + mount(); + const user = await fillRecipe(); + await user.click(screen.getByRole('button', { name: 'Publish recipe' })); + expect( + await screen.findByRole('heading', { name: 'Saved recipe destination' }), + ).toBeInTheDocument(); + expect(input).toMatchObject({ + prepMinutes: 5, + cookMinutes: 0, + difficulty: 'medium', + imageUrl: null, + category: 'soup', + }); +}); +it('preserves input after a failed save and allows retry', async () => { + let fail = true; + mockRecipeFetch(() => + fail + ? { errors: [{ extensions: { code: 'BAD_USER_INPUT' } }] } + : { data: { createRecipe: apiRecipe } }, + ); + mount(); + const user = await fillRecipe(); + await user.click(screen.getByRole('button', { name: 'Publish recipe' })); + expect( + await screen.findByText('Check the recipe fields and try again.'), + ).toBeInTheDocument(); + expect(screen.getByLabelText(/Recipe title/)).toHaveValue('New soup'); + fail = false; + await user.click(screen.getByRole('button', { name: 'Publish recipe' })); + expect( + await screen.findByRole('heading', { name: 'Saved recipe destination' }), + ).toBeInTheDocument(); +}); +it('loads an owned recipe for editing and preserves image, cuisine, notes and private visibility', async () => { + let input: unknown; + mockRecipeFetch((operation, variables) => { + const recipe = { + ...apiRecipe, + isCreatedByCurrentUser: true, + visibility: 'private', + cuisine: 'Nordic', + imageUrl: 'https://example.com/soup.jpg', + ingredients: [{ ...apiRecipe.ingredients[0], note: 'Warm', unit: 'tsp' }], + }; + if (operation === 'UpdateRecipe') { + input = variables.input; + return { data: { updateRecipe: recipe } }; } + return { data: { recipe } }; }); - - it('shows local success feedback for a valid recipe', async () => { - const user = userEvent.setup(); - - render(); - - await user.type(screen.getByLabelText(/Recipe title/), 'Pasta'); - await user.type(screen.getByLabelText(/Cooking time/), '20'); - await user.type(screen.getByLabelText(/Servings/), '2'); - await user.selectOptions(screen.getByLabelText(/Category/), 'dinner'); - await user.type(screen.getByLabelText('Ingredient 1'), '200g pasta'); - await user.type(screen.getByLabelText('Ingredient 1 amount'), '200'); - await user.selectOptions(screen.getByLabelText('Ingredient 1 unit'), 'g'); - await user.type(screen.getByLabelText('Step 1'), 'Boil the pasta.'); - await user.click(screen.getByRole('button', { name: 'Publish recipe' })); - - expect(screen.getByText('Recipe ready to publish')).toBeInTheDocument(); - expect( - screen.getByText(/No data was sent to a server/), - ).toBeInTheDocument(); + mount('/recipes/' + apiRecipe.id + '/edit'); + await screen.findByRole('heading', { name: 'Edit Recipe' }); + expect(screen.getByLabelText('Private')).toBeChecked(); + const user = userEvent.setup(); + await user.click(screen.getByRole('button', { name: 'Save changes' })); + await screen.findByRole('heading', { name: 'Saved recipe destination' }); + expect(input).toMatchObject({ + visibility: 'private', + cuisine: 'Nordic', + imageUrl: 'https://example.com/soup.jpg', + ingredients: [expect.objectContaining({ unit: 'tsp', note: 'Warm' })], }); + expect( + (input as { ingredients: object[] }).ingredients[0], + ).not.toHaveProperty('id'); }); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index 3709c67..09d73e2 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -3,18 +3,12 @@ import { useEffect, useRef, useState, - type DragEvent, type FormEvent, type PointerEvent as ReactPointerEvent, } from 'react'; -import { - DeleteIcon, - DragHandleIcon, - UploadPhotoIcon, -} from '../../icons/actions'; +import { DeleteIcon, DragHandleIcon } from '../../icons/actions'; import Button from '../../components/ui/Button/Button'; -import Dialog from '../../components/ui/Dialog/Dialog'; import Field from '../../components/ui/Field/Field'; import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage'; import IconButton from '../../components/ui/IconButton/IconButton'; @@ -23,7 +17,17 @@ import Radio from '../../components/ui/Radio/Radio'; import RadioGroup from '../../components/ui/Radio/RadioGroup'; import Select from '../../components/ui/Select/Select'; import Textarea from '../../components/ui/Textarea/Textarea'; -import Cropper, { type Area } from 'react-easy-crop'; +import { useNavigate, useParams } from 'react-router-dom'; +import type { Recipe } from '../../types/recipe'; +import { + getRecipe, + writeRecipe, + recipeErrorMessage, + type RecipeInput, +} from './recipeApi'; +import { useRecipeQuery } from './useRecipeQuery'; +import RecipeQueryStatus from './RecipeQueryStatus'; +import LinkButton from '../../components/ui/LinkButton/LinkButton'; import './RecipeCreatePage.css'; @@ -31,6 +35,8 @@ type RecipeErrors = { title?: string; description?: string; cookingTime?: string; + prepTime?: string; + difficulty?: string; servings?: string; category?: string; visibility?: string; @@ -45,51 +51,15 @@ type IngredientFieldErrors = { unit?: string; }; -type FormStatus = 'idle' | 'draft' | 'published'; +type FormStatus = 'idle' | 'draft'; type IngredientDraft = { name: string; amount: string; unit: string; + note?: string; }; -const MAX_IMAGE_SIZE = 5 * 1024 * 1024; -const ACCEPTED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp']; - -async function createCroppedImage(imageUrl: string, crop: Area) { - const image = new Image(); - image.src = imageUrl; - await new Promise((resolve, reject) => { - image.onload = () => resolve(); - image.onerror = () => reject(new Error('Unable to load image.')); - }); - - const canvas = document.createElement('canvas'); - canvas.width = crop.width; - canvas.height = crop.height; - const context = canvas.getContext('2d'); - if (!context) throw new Error('Unable to prepare image crop.'); - - context.drawImage( - image, - crop.x, - crop.y, - crop.width, - crop.height, - 0, - 0, - crop.width, - crop.height, - ); - - return new Promise((resolve, reject) => { - canvas.toBlob((blob) => { - if (blob) resolve(blob); - else reject(new Error('Unable to create image crop.')); - }, 'image/jpeg'); - }); -} - function moveItem(items: T[], fromIndex: number, toIndex: number) { const nextItems = [...items]; const [movedItem] = nextItems.splice(fromIndex, 1); @@ -98,43 +68,44 @@ function moveItem(items: T[], fromIndex: number, toIndex: number) { return nextItems; } -function RecipeCreatePage() { - const [title, setTitle] = useState(''); - const [description, setDescription] = useState(''); - const [cookingTime, setCookingTime] = useState(''); - const [servings, setServings] = useState(''); - const [category, setCategory] = useState(''); - const [tags, setTags] = useState(''); - const [visibility, setVisibility] = useState('public'); - const [imageName, setImageName] = useState(''); - const [imagePreviewUrl, setImagePreviewUrl] = useState(''); - const [imageFile, setImageFile] = useState(); - const [isDraggingImage, setIsDraggingImage] = useState(false); - const imageInputRef = useRef(null); - const [ingredients, setIngredients] = useState([ - { name: '', amount: '', unit: 'g' }, - ]); - const [instructions, setInstructions] = useState(['']); +function RecipeEditor({ recipe }: { recipe?: Recipe }) { + const navigate = useNavigate(); + const busyRef = useRef(false); + const [pending, setPending] = useState(false); + const [submitError, setSubmitError] = useState(''); + const [title, setTitle] = useState(recipe?.title ?? ''); + const [description, setDescription] = useState(recipe?.description ?? ''); + const [cookingTime, setCookingTime] = useState( + recipe ? String(recipe.cookMinutes) : '', + ); + const [servings, setServings] = useState( + recipe ? String(recipe.servings) : '', + ); + const [category, setCategory] = useState(recipe?.category ?? ''); + const [tags, setTags] = useState(recipe?.tags.join(', ') ?? ''); + const [visibility, setVisibility] = useState(recipe?.visibility ?? 'public'); + const [prepTime, setPrepTime] = useState( + recipe ? String(recipe.prepMinutes) : '', + ); + const [difficulty, setDifficulty] = useState(recipe?.difficulty ?? ''); + const [ingredients, setIngredients] = useState( + recipe?.ingredients.map((item) => ({ + ...item, + amount: String(item.amount), + })) ?? [{ name: '', amount: '', unit: 'g' }], + ); + const [instructions, setInstructions] = useState( + recipe?.instructions.map((item) => item.text) ?? [''], + ); const [draggingRow, setDraggingRow] = useState< { type: 'ingredient' | 'instruction'; index: number } | undefined >(); const [errors, setErrors] = useState({}); const [status, setStatus] = useState('idle'); - const [cropImageUrl, setCropImageUrl] = useState(''); - const [cropFileName, setCropFileName] = useState(''); - const [crop, setCrop] = useState({ x: 0, y: 0 }); - const [zoom, setZoom] = useState(1); - const [croppedAreaPixels, setCroppedAreaPixels] = useState(); const pointerDragRef = useRef< { type: 'ingredient' | 'instruction'; index: number } | undefined >(undefined); - useEffect(() => { - return () => { - if (imagePreviewUrl) URL.revokeObjectURL(imagePreviewUrl); - }; - }, [imagePreviewUrl]); - function clearError(key: keyof RecipeErrors) { setErrors((currentErrors) => { const nextErrors = { ...currentErrors }; @@ -313,96 +284,6 @@ function RecipeCreatePage() { setDraggingRow({ type, index }); } - function handleImageChange(file: File | undefined) { - clearError('image'); - - if (!file) { - setImageName(''); - setImagePreviewUrl(''); - return; - } - - if (!ACCEPTED_IMAGE_TYPES.includes(file.type)) { - setErrors((currentErrors) => ({ - ...currentErrors, - image: 'Choose a JPG, PNG, or WebP image.', - })); - setImageName(''); - setImagePreviewUrl(''); - return; - } - - if (file.size > MAX_IMAGE_SIZE) { - setErrors((currentErrors) => ({ - ...currentErrors, - image: 'Choose an image smaller than 5 MB.', - })); - setImageName(''); - setImagePreviewUrl(''); - return; - } - - if (cropImageUrl) URL.revokeObjectURL(cropImageUrl); - const nextImageUrl = URL.createObjectURL(file); - setCropImageUrl(nextImageUrl); - setCropFileName(file.name); - setCrop({ x: 0, y: 0 }); - setZoom(1); - } - - function closeCropDialog() { - if (cropImageUrl) URL.revokeObjectURL(cropImageUrl); - setCropImageUrl(''); - setCropFileName(''); - setCroppedAreaPixels(undefined); - } - - async function applyCrop() { - if (!cropImageUrl || !croppedAreaPixels) { - closeCropDialog(); - return; - } - - try { - const croppedBlob = await createCroppedImage( - cropImageUrl, - croppedAreaPixels, - ); - const croppedFileName = `${ - cropFileName.replace(/\.[^/.]+$/, '') || 'recipe-image' - }.jpg`; - const croppedFile = new File([croppedBlob], croppedFileName, { - type: 'image/jpeg', - }); - setImageFile(croppedFile); - setImageName(croppedFile.name); - setImagePreviewUrl(URL.createObjectURL(croppedBlob)); - closeCropDialog(); - } catch { - setErrors((currentErrors) => ({ - ...currentErrors, - image: 'Unable to crop this image. Please choose another image.', - })); - closeCropDialog(); - } - } - - function handleImageDrop(event: DragEvent) { - event.preventDefault(); - setIsDraggingImage(false); - handleImageChange(event.dataTransfer.files[0]); - } - - function removeImage() { - clearError('image'); - closeCropDialog(); - setImageFile(undefined); - setImageName(''); - setImagePreviewUrl(''); - setIsDraggingImage(false); - if (imageInputRef.current) imageInputRef.current.value = ''; - } - function validateForm(): RecipeErrors { const nextErrors: RecipeErrors = {}; @@ -410,11 +291,25 @@ function RecipeCreatePage() { if (description.trim().length > 200) { nextErrors.description = 'Keep the description under 200 characters.'; } - if (!cookingTime || Number(cookingTime) < 1) { - nextErrors.cookingTime = 'Enter a cooking time of at least 1 minute.'; - } - if (!servings || Number(servings) < 1) { - nextErrors.servings = 'Enter at least 1 serving.'; + const validMinutes = (value: string) => + value !== '' && + Number.isInteger(Number(value)) && + Number(value) >= 0 && + Number(value) <= 10080; + if (!validMinutes(cookingTime)) + nextErrors.cookingTime = 'Enter cooking minutes from 0 to 10080.'; + if (!validMinutes(prepTime)) + nextErrors.prepTime = 'Enter preparation minutes from 0 to 10080.'; + if (!difficulty) nextErrors.difficulty = 'Choose a difficulty.'; + if (title.trim().length > 160) + nextErrors.title = 'Keep the title under 160 characters.'; + if ( + !servings || + !Number.isInteger(Number(servings)) || + Number(servings) < 1 || + Number(servings) > 1000 + ) { + nextErrors.servings = 'Enter whole servings from 1 to 1000.'; } if (!category) nextErrors.category = 'Choose a recipe category.'; if (!visibility) { @@ -422,12 +317,23 @@ function RecipeCreatePage() { } const ingredientErrors = ingredients.map((ingredient) => ({ - name: ingredient.name.trim() ? undefined : 'Enter an ingredient name.', + name: !ingredient.name.trim() + ? 'Enter an ingredient name.' + : ingredient.name.trim().length > 200 + ? 'Keep ingredient names under 200 characters.' + : undefined, amount: - ingredient.amount.trim() && Number(ingredient.amount) > 0 + ingredient.amount.trim() && + Number(ingredient.amount) > 0 && + Number(ingredient.amount) <= 99999999.9999 && + Math.round(Number(ingredient.amount) * 10000) / 10000 === + Number(ingredient.amount) ? undefined : 'Enter a positive amount.', - unit: ingredient.unit ? undefined : 'Choose an ingredient unit.', + unit: + ingredient.unit.length <= 50 + ? undefined + : 'Keep units under 50 characters.', })); if ( ingredientErrors.some((ingredientError) => @@ -437,7 +343,11 @@ function RecipeCreatePage() { nextErrors.ingredients = ingredientErrors; const instructionErrors = instructions.map((instruction) => - instruction.trim() ? '' : 'Add an instruction.', + !instruction.trim() + ? 'Add an instruction.' + : instruction.trim().length > 5000 + ? 'Keep instructions under 5000 characters.' + : '', ); if (instructionErrors.some(Boolean)) { nextErrors.instructions = instructionErrors; @@ -446,8 +356,9 @@ function RecipeCreatePage() { return nextErrors; } - function handleSubmit(event: FormEvent) { + async function handleSubmit(event: FormEvent) { event.preventDefault(); + if (busyRef.current) return; const nextErrors = validateForm(); setErrors(nextErrors); @@ -456,6 +367,8 @@ function RecipeCreatePage() { const firstIngredientError = nextErrors.ingredients?.[0]; const firstInvalidId = [ { id: 'recipe-title', invalid: Boolean(nextErrors.title) }, + { id: 'prep-time', invalid: Boolean(nextErrors.prepTime) }, + { id: 'difficulty', invalid: Boolean(nextErrors.difficulty) }, { id: 'cooking-time', invalid: Boolean(nextErrors.cookingTime) }, { id: 'servings', invalid: Boolean(nextErrors.servings) }, { id: 'category', invalid: Boolean(nextErrors.category) }, @@ -485,7 +398,41 @@ function RecipeCreatePage() { return; } - setStatus('published'); + busyRef.current = true; + setPending(true); + setSubmitError(''); + try { + const input: RecipeInput = { + title: title.trim(), + description: description.trim(), + category: category as RecipeInput['category'], + difficulty: difficulty as RecipeInput['difficulty'], + visibility, + prepMinutes: Number(prepTime), + cookMinutes: Number(cookingTime), + servings: Number(servings), + ingredients: ingredients.map((item) => ({ + name: item.name.trim(), + amount: Number(item.amount), + unit: item.unit, + note: item.note, + })), + instructions: instructions.map((text) => text.trim()), + tags: tags + .split(',') + .map((tag) => tag.trim()) + .filter(Boolean), + imageUrl: recipe?.imageUrl ?? null, + cuisine: recipe?.cuisine || null, + }; + const saved = await writeRecipe(input, recipe?.id); + navigate('/recipes/' + saved.id, { replace: Boolean(recipe) }); + } catch (error) { + setSubmitError(recipeErrorMessage(error)); + } finally { + busyRef.current = false; + setPending(false); + } } return ( @@ -495,7 +442,9 @@ function RecipeCreatePage() { >

Share with the community

-

Add Recipe

+

+ {recipe ? 'Edit Recipe' : 'Add Recipe'} +

Share your favorite recipe with the community.

@@ -506,14 +455,16 @@ function RecipeCreatePage() { onSubmit={handleSubmit} noValidate > -
- {status === 'published' && ( - - Your recipe has been prepared locally. No data was sent to a - server. +
+ {submitError && ( + + {submitError} )} - {status === 'draft' && ( Your draft is available in this form until you leave the page. @@ -561,135 +512,12 @@ function RecipeCreatePage() {
-
- {imagePreviewUrl ? ( -
- Selected recipe -
- - {imageFile?.name ?? imageName} - - -
-
- ) : ( - - )} - - Upload a JPG, PNG, or WebP image up to 5 MB. - - {errors.image && ( - - )} -
+

+ Image uploads are not available yet. Existing recipe images are + kept when editing. +

- - - - - } - > -
- setCroppedAreaPixels(area)} - /> -
- -
-
+ { + setPrepTime(event.target.value); + clearError('prepTime'); + }} + /> + Lunch +
@@ -771,15 +638,27 @@ function RecipeCreatePage() { error={errors.visibility} onChange={(event) => { if (event.target instanceof HTMLInputElement) { - setVisibility(event.target.value); + setVisibility( + event.target.value as RecipeInput['visibility'], + ); clearError('visibility'); } }} layout="horizontal" required > - - + +
@@ -848,11 +727,18 @@ function RecipeCreatePage() { aria-label={`Ingredient ${index + 1} unit`} value={ingredient.unit} error={errors.ingredients?.[index]?.unit} - required onChange={(event) => updateIngredient(index, 'unit', event.target.value) } > + {!['', 'g', 'kg', 'l', 'dl', 'ss', 'ts', 'stk'].includes( + ingredient.unit, + ) && ( + + )} + @@ -959,12 +845,34 @@ function RecipeCreatePage() { > Save draft - +
- + ); } +function RecipeCreatePage() { + const { id } = useParams(); + const load = useCallback( + (signal: AbortSignal) => + id ? getRecipe(id, signal) : Promise.resolve(null), + [id], + ); + const query = useRecipeQuery(id ?? 'new', load); + if (id && (query.loading || query.error)) + return ; + if (id && !query.data?.isCreatedByCurrentUser) + return ( +
+

Recipe unavailable

+

You can only edit your own recipes.

+ Back to My Cookbook +
+ ); + return ; +} export default RecipeCreatePage; diff --git a/apps/web/src/features/recipes/RecipeQueryStatus.tsx b/apps/web/src/features/recipes/RecipeQueryStatus.tsx new file mode 100644 index 0000000..2e89bcf --- /dev/null +++ b/apps/web/src/features/recipes/RecipeQueryStatus.tsx @@ -0,0 +1,21 @@ +import Button from '../../components/ui/Button/Button'; + +export default function RecipeQueryStatus({ + loading, + error, + retry, +}: { + loading: boolean; + error?: string; + retry: () => void; +}) { + if (loading) return

Loading recipes…

; + if (error) + return ( +
+

{error}

+ +
+ ); + return null; +} diff --git a/apps/web/src/features/recipes/recipeApi.ts b/apps/web/src/features/recipes/recipeApi.ts new file mode 100644 index 0000000..48dd77c --- /dev/null +++ b/apps/web/src/features/recipes/recipeApi.ts @@ -0,0 +1,92 @@ +import { create } from 'zustand'; +import { z } from 'zod'; +import { + RecipesDocument, + CookbookDocument, + RecipeDocument, + CreateRecipeDocument, + UpdateRecipeDocument, + DeleteRecipeDocument, + SaveRecipeDocument, + UnsaveRecipeDocument, + type RecipeFieldsFragment, + type RecipeInput, + type RecipeListInput, + type CookbookScope, +} from '../../../../../contracts/generated'; +import { ApiError, graphqlRequest } from '../../lib/graphqlClient'; +import type { Recipe } from '../../types/recipe'; + +export const useRecipeChanges = create(() => ({ revision: 0 })); +function invalidateRecipes() { + useRecipeChanges.setState((state) => ({ revision: state.revision + 1 })); +} + +export function toRecipe(recipe: RecipeFieldsFragment): Recipe { + return { + ...recipe, + cuisine: recipe.cuisine ?? '', + ingredients: recipe.ingredients.map((ingredient) => ({ + ...ingredient, + note: ingredient.note ?? undefined, + })), + }; +} + +export async function listRecipes( + input: RecipeListInput, + scope?: CookbookScope, + signal?: AbortSignal, +) { + const page = scope + ? (await graphqlRequest(CookbookDocument, { input, scope }, signal)) + .cookbook + : (await graphqlRequest(RecipesDocument, { input }, signal)).recipes; + return { + items: page.items.map(toRecipe), + totalItems: page.totalCount, + pageCount: page.totalPages, + page: page.page, + pageSize: page.pageSize, + }; +} + +export async function getRecipe(id: string, signal?: AbortSignal) { + if (!z.uuid().safeParse(id).success) return null; + const { recipe } = await graphqlRequest(RecipeDocument, { id }, signal); + return recipe ? toRecipe(recipe) : null; +} + +export async function writeRecipe(input: RecipeInput, id?: string) { + const recipe = id + ? (await graphqlRequest(UpdateRecipeDocument, { id, input })).updateRecipe + : (await graphqlRequest(CreateRecipeDocument, { input })).createRecipe; + invalidateRecipes(); + return toRecipe(recipe); +} + +export async function deleteRecipe(id: string) { + await graphqlRequest(DeleteRecipeDocument, { id }); + invalidateRecipes(); +} + +export async function changeRecipeSaved(id: string, saved: boolean) { + if (saved) await graphqlRequest(SaveRecipeDocument, { id }); + else await graphqlRequest(UnsaveRecipeDocument, { id }); + invalidateRecipes(); +} + +export function recipeErrorMessage(error: unknown) { + if (error instanceof ApiError) { + const messages: Record = { + UNAUTHENTICATED: 'Your session has expired. Please sign in again.', + FORBIDDEN: 'You do not have permission to perform this action.', + NOT_FOUND: 'This recipe is unavailable or you no longer have access.', + BAD_USER_INPUT: 'Check the recipe fields and try again.', + }; + return messages[error.code] ?? error.message; + } + return 'Unable to complete the request. Please try again.'; +} + +export type { RecipeInput }; diff --git a/apps/web/src/features/recipes/useRecipeQuery.ts b/apps/web/src/features/recipes/useRecipeQuery.ts new file mode 100644 index 0000000..9e9f049 --- /dev/null +++ b/apps/web/src/features/recipes/useRecipeQuery.ts @@ -0,0 +1,43 @@ +import { useEffect, useState } from 'react'; +import { useAppStore } from '../../store'; +import { recipeErrorMessage, useRecipeChanges } from './recipeApi'; + +export function useRecipeQuery( + key: string, + load: (signal: AbortSignal) => Promise, +) { + const userId = useAppStore((state) => state.currentUser?.id); + const sessionStatus = useAppStore((state) => state.sessionStatus); + const revision = useRecipeChanges((state) => state.revision); + const [attempt, setAttempt] = useState(0); + const requestKey = JSON.stringify([ + key, + userId, + sessionStatus, + revision, + attempt, + ]); + const [state, setState] = useState<{ key: string; data?: T; error?: string }>( + { key: '' }, + ); + useEffect(() => { + const controller = new AbortController(); + load(controller.signal).then( + (data) => { + if (!controller.signal.aborted) setState({ key: requestKey, data }); + }, + (error: unknown) => { + if (!controller.signal.aborted) + setState({ key: requestKey, error: recipeErrorMessage(error) }); + }, + ); + return () => controller.abort(); + }, [requestKey, load]); + const current = state.key === requestKey ? state : undefined; + return { + data: current?.data, + error: current?.error, + loading: !current, + retry: () => setAttempt((value) => value + 1), + }; +} diff --git a/apps/web/src/lib/graphqlClient.ts b/apps/web/src/lib/graphqlClient.ts new file mode 100644 index 0000000..4583a23 --- /dev/null +++ b/apps/web/src/lib/graphqlClient.ts @@ -0,0 +1,68 @@ +import { print } from 'graphql'; +import type { TypedDocumentNode } from '@graphql-typed-document-node/core'; + +const GRAPHQL_URL = import.meta.env.DEV ? '/graphql' : '/project2/api/graphql'; + +export class ApiError extends Error { + constructor( + public code: string, + message: string, + ) { + super(message); + } +} + +export async function graphqlRequest( + document: TypedDocumentNode, + variables: V, + signal?: AbortSignal, +): Promise { + let response: Response; + try { + response = await fetch(GRAPHQL_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Requested-With': 'recipe-platform', + }, + credentials: 'same-origin', + body: JSON.stringify({ query: print(document), variables }), + signal, + }); + } catch (error) { + if (signal?.aborted) throw error; + throw new ApiError( + 'NETWORK_ERROR', + 'Unable to connect. Check your connection and try again.', + ); + } + if (!response.ok) + throw new ApiError( + 'API_ERROR', + 'The service is temporarily unavailable. Please try again.', + ); + let result: { data?: T; errors?: Array<{ extensions?: { code?: string } }> }; + try { + const json: unknown = await response.json(); + if (!json || typeof json !== 'object' || Array.isArray(json)) + throw new Error(); + result = json; + } catch { + throw new ApiError( + 'API_ERROR', + 'The service returned an invalid response. Please try again.', + ); + } + const error = result.errors?.[0]; + if (error) + throw new ApiError( + error.extensions?.code ?? 'API_ERROR', + 'The request could not be completed.', + ); + if (!result.data) + throw new ApiError( + 'API_ERROR', + 'The service returned no data. Please try again.', + ); + return result.data; +} diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 6213b77..9386b69 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -1,6 +1,5 @@ import { create } from 'zustand'; -import { recipes } from './data/recipes'; import { getCurrentUser, loginUser, @@ -21,10 +20,6 @@ export type SessionStatus = // Remove credentials left by the old token-based client during migration. const LEGACY_TOKEN_KEY = 'recipe-platform-session-token'; -export const INITIAL_SAVED_RECIPE_IDS = recipes - .filter((recipe) => recipe.isSaved) - .map((recipe) => recipe.id); - interface AppState { search: string; currentUser: User | null; @@ -37,22 +32,12 @@ interface AppState { restoreSession: () => Promise; signOut: () => Promise; - - savedRecipeIds: string[]; - setRecipeSaved: (recipeId: string, saved: boolean) => void; - - userRatings: Record; - setUserRating: (recipeId: string, rating: number) => void; - - removeUserRating: (recipeId: string) => void; } export const useAppStore = create((set) => ({ search: '', currentUser: null, sessionStatus: 'restoring', - savedRecipeIds: [...INITIAL_SAVED_RECIPE_IDS], - userRatings: {}, setSearch: (search) => set({ search }), @@ -107,44 +92,4 @@ export const useAppStore = create((set) => ({ localStorage.removeItem(LEGACY_TOKEN_KEY); set({ currentUser: null, sessionStatus: 'anonymous' }); }, - - removeUserRating: (recipeId) => - set((state) => { - const nextUserRatings = { ...state.userRatings }; - - delete nextUserRatings[recipeId]; - - return { - userRatings: nextUserRatings, - }; - }), - - setRecipeSaved: (recipeId, saved) => - set((state) => { - if (saved) { - if (state.savedRecipeIds.includes(recipeId)) { - return { - savedRecipeIds: state.savedRecipeIds, - }; - } - - return { - savedRecipeIds: [...state.savedRecipeIds, recipeId], - }; - } - - return { - savedRecipeIds: state.savedRecipeIds.filter( - (savedRecipeId) => savedRecipeId !== recipeId, - ), - }; - }), - - setUserRating: (recipeId, rating) => - set((state) => ({ - userRatings: { - ...state.userRatings, - [recipeId]: Math.min(5, Math.max(1, Math.round(rating))), - }, - })), })); diff --git a/apps/web/src/test/recipeApiFixtures.ts b/apps/web/src/test/recipeApiFixtures.ts new file mode 100644 index 0000000..539168c --- /dev/null +++ b/apps/web/src/test/recipeApiFixtures.ts @@ -0,0 +1,58 @@ +import { vi } from 'vitest'; +import type { RecipeFieldsFragment } from '../../../../contracts/generated'; + +export const apiRecipe: RecipeFieldsFragment = { + id: '11111111-1111-4111-8111-111111111111', + title: 'API soup', + description: 'A simple soup', + category: 'soup', + cuisine: null, + difficulty: 'easy', + visibility: 'public', + imageUrl: null, + sourceRecipeId: null, + prepMinutes: 5, + cookMinutes: 10, + servings: 2, + createdAt: '2026-10-22T12:00:00Z', + updatedAt: '2026-10-22T12:00:00Z', + author: { id: '22222222-2222-4222-8222-222222222222', name: 'Chef' }, + ingredients: [ + { id: 'ingredient-1', name: 'Water', amount: 1, unit: 'l', note: null }, + ], + instructions: [{ step: 1, text: 'Boil the water.' }], + tags: ['quick'], + rating: { average: 4, count: 2 }, + saveCount: 0, + isSaved: false, + isCreatedByCurrentUser: false, +}; +export const apiUser = { + id: apiRecipe.author.id, + name: 'Chef', + email: 'chef@example.com', +}; +export function apiPage(items = [apiRecipe], overrides = {}) { + return { + items, + totalCount: items.length, + totalPages: items.length ? 1 : 0, + page: 1, + pageSize: 6, + ...overrides, + }; +} +export function mockRecipeFetch( + handler: ( + operation: string, + variables: Record, + ) => unknown | Promise, +) { + const fetch = vi.fn(async (_url: string, options: RequestInit) => { + const body = JSON.parse(String(options.body)); + const operation = /(?:query|mutation)\s+(\w+)/.exec(body.query)?.[1] ?? ''; + return Response.json(await handler(operation, body.variables)); + }); + vi.stubGlobal('fetch', fetch); + return fetch; +} diff --git a/apps/web/src/types/recipe.ts b/apps/web/src/types/recipe.ts index 25ad95b..4d7f1a0 100644 --- a/apps/web/src/types/recipe.ts +++ b/apps/web/src/types/recipe.ts @@ -1,6 +1,11 @@ -export type RecipeVisibility = 'public' | 'private'; - -export type RecipeDifficulty = 'easy' | 'medium' | 'hard'; +import type { + RecipeVisibility, + RecipeDifficulty, +} from '../../../../contracts/generated'; +export type { + RecipeVisibility, + RecipeDifficulty, +} from '../../../../contracts/generated'; export interface UserSummary { id: string; diff --git a/docs/frontend-integration.md b/docs/frontend-integration.md new file mode 100644 index 0000000..437d602 --- /dev/null +++ b/docs/frontend-integration.md @@ -0,0 +1,47 @@ +# Frontend integration checklist + +## Implemented + +- [x] Use a shared, typed GraphQL client with the existing cookie and request headers. +- [x] Load Explore, Cookbook and recipe details from the API. +- [x] Preserve URL search, filters, scope and server pagination. +- [x] Display only the supported newest-first sorting option. +- [x] Describe search accurately as title/description search. +- [x] Persist Save/Unsave and refetch recipe views after successful mutations. +- [x] Remove mock saved recipes and local ratings from application state. +- [x] Cancel obsolete reads and isolate results by authenticated user. +- [x] Create recipes with explicit difficulty, preparation and cooking times. +- [x] Load owned recipes at `/recipes/:id/edit` and submit complete updates. +- [x] Preserve existing image URLs, cuisine and ingredient notes when editing. +- [x] Delete owned recipes after confirmation. +- [x] Handle loading, empty, unavailable and retryable error states separately. +- [x] Keep form data after failed mutations and prevent duplicate submissions. +- [x] Temporarily hide image uploads/cropping and disable rating actions. +- [x] Replace mock-page assertions with API integration tests. +- [x] Add a real API/PostgreSQL browser test for recipe CRUD and Save/Unsave. + +## Verification + +Run `npm run check`, `npm run test:api`, `npm run test:db` and +`npm run test:e2e`. Install the browser with `npx playwright install chromium` +if needed. + +The recipe browser test requires `DATABASE_URL` (loaded from `.env` when present) +and CREATE SCHEMA permission. It applies migrations to a unique temporary schema +and removes that schema afterward. Use a development/test database. Without a +database URL, that browser test is explicitly skipped; shell/auth browser tests +remain available. + +## Follow-up work + +- [ ] Add ingredient/tag search and agree on normalization rules in D3. +- [ ] Implement additional sorting in the backend before pagination. +- [ ] Define trending behavior independently of the old fixed mock date. +- [ ] Add image storage/uploading that returns durable URLs to recipe CRUD. +- [ ] Add persistent rating mutations before enabling rating controls. +- [ ] Consider separate SQL summary/detail reads and domain-error translation. +- [ ] Verify the deployed VM flow after merge and deployment. + +The draft button keeps edits in the current form only. Drafts are not persisted +across navigation or reload. Mock query modules remain solely for prototype +tests and are not imported by production pages. diff --git a/docs/recipe-api.md b/docs/recipe-api.md index f1060a0..d555956 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -32,8 +32,8 @@ og importer tilhørende dokumenter og typer fra | Save / Unsave | `SaveRecipeDocument` / `UnsaveRecipeDocument` | | Cookbook | `CookbookDocument` | -Eksempelet under kan ligge i `apps/web/src/features/recipes/recipeApi.ts` når -frontend kobles til i steg 3. Det oppretter en oppskrift for innlogget bruker. +Frontend bruker nå `apps/web/src/features/recipes/recipeApi.ts` og den delte +klienten `apps/web/src/lib/graphqlClient.ts`. Eksempelet under viser transporten. Det oppretter en oppskrift for innlogget bruker. Samme URL, headere og cookie-innstilling brukes for de øvrige operasjonene. ```ts @@ -99,7 +99,8 @@ operasjonen er ikke en delvis oppdatering. Listeoperasjoner returnerer Ved frontendkobling må komponenten håndtere lasting og feil, beholde formdata ved feil og oppdatere relevante lister etter en vellykket mutation. -Oppskriftssidene bruker fortsatt mock-data frem til steg 3. +Explore, Cookbook, Detail og oppskriftsskjemaet bruker nå API-et. Se +[frontend integration checklist](frontend-integration.md). ## Autentisering @@ -152,13 +153,13 @@ fire desimaler og passe `numeric(12,4)`. Porsjoner er heltall 1–1000, tider er heltall 0–10080 minutter per felt, beskrivelse maksimalt 200 tegn. Tagger trimmes, normaliseres til små bokstaver og dedupliseres. Kategori bruker databasens fem nøkler. -Frontend må kobles separat ved de eksisterende data-grensene. Spesielt: +Frontend er koblet ved de eksisterende data-grensene. Integrasjonen følger disse reglene: - Add Recipe har nå separate felt for navn, mengde og enhet. Konverter - mengdeverdien fra formtekst til tall. Legg til eksplisitte felt for difficulty, - prepMinutes og cookMinutes før integrasjonen; ikke gjett vanskelighetsgrad + mengdeverdien fra formtekst til tall. Skjemaet har eksplisitte felt for difficulty, + prepMinutes og cookMinutes; ikke gjett vanskelighetsgrad eller fordel den eksisterende cookingTime-verdien automatisk. -- Explore/Detail må bytte mock-data med de genererte operasjonene. +- Explore/Detail bruker de genererte operasjonene. - Send samme cookie og forespørselshoder som auth-klienten på oppskriftsoperasjoner. - Etter mutasjoner: refetch liste/detail/cookbook slik at lagringstilstanden er lik. - `cuisine` er nullable; en frontend-mapper må håndtere manglende verdi. @@ -180,18 +181,18 @@ ukjente oppskrifter gir samme feil og avslører ikke private data. Bruk de regenererte kontraktene; ingen databasemigrasjon er nødvendig. - Søk gjelder foreløpig bare tittel/beskrivelse. Mock-søket inkluderer også ingredienser/tagger og normaliserer bindestrek, understrek og mellomrom mer - omfattende. Beskriv det faktiske søkeomfanget i UI-et ved integrasjon. + omfattende. UI-et beskriver det faktiske søkeomfanget. Behold søkeinput ved datagrensen; ingrediens-/taggsøk og felles normaliseringsregler avklares i D3 og implementeres i backend. -- Vis bare støttet sortering ved integrasjon: nyeste først. Cookbook sitt +- UI-et viser bare støttet sortering: nyeste først. Cookbook sitt «recently updated» er ikke det samme som opprettelsesdato. Flere sorteringer skal implementeres i backend før LIMIT/OFFSET, med stabil tie-breaker og tester over flere sider. Ikke sorter eller filtrer én hentet side lokalt. -- Midlertidig opprettes oppskrifter uten opplastede bilder. Skjul/deaktiver - filvalg og beskjæring med en tydelig forklaring ved integrasjon. Ikke send +- Midlertidig opprettes oppskrifter uten opplastede bilder. Filvalg og + beskjæring er skjult med en tydelig forklaring. Ikke send lokale blob-/data-URL-er som imageUrl. Senere kan en separat opplastingstjeneste returnere en varig HTTP(S)-URL til eksisterende CRUD-input. -- Frontendintegrasjonen gjøres i en egen branch etter API-endringene. +- Frontendintegrasjonen ligger i en egen branch etter API-endringene. Separate liste-/detaljspørringer i SQL og domenefeil som oversettes til GraphQL-feil ved resolvergrensen vurderes i senere, avgrensede endringer. Listeoperasjonene henter foreløpig komplette oppskrifter også i databasen. @@ -235,7 +236,7 @@ Passordet lagres som Argon2-hash. På Linux: `SEED_PASSWORD='...' npm run db:see - D2-05/06/08/10: API-testmønster, autentisert context, reads/visibility og create er implementert, sammen med eierstyrt update/delete. - D2-12: persistent Save/Unsave/Cookbook er implementert. -- D2-07/09/11/13: frontendintegrasjon gjenstår; eksisterende auth-UI virker fortsatt. +- D2-07/09/11/13: frontend er koblet til oppskrifts-API-et, inkludert CRUD og Save/Unsave/Cookbook. - D2-02/15/16: VM-deploy og full nettleserdemonstrasjon må kontrolleres etter integrasjon. Bruk eksisterende Apache/systemd-oppsett og `/project2/api/graphql`. - D2-14: ratingmutasjoner/reviews er utsatt. Avansert sortering/søk er D3. diff --git a/e2e/auth-cookie.spec.ts b/e2e/auth-cookie.spec.ts index 05703fb..b25bffc 100644 --- a/e2e/auth-cookie.spec.ts +++ b/e2e/auth-cookie.spec.ts @@ -43,6 +43,23 @@ test('login uses an HttpOnly cookie, survives refresh and revokes logout', async }) => { // Proxy to the real Yoga HTTP endpoint with a deterministic service, no live DB. await page.route('**/project2/api/graphql', async (route) => { + const body = route.request().postDataJSON() as { query: string }; + if (body.query.includes('query Cookbook')) { + await route.fulfill({ + json: { + data: { + cookbook: { + items: [], + totalCount: 0, + totalPages: 0, + page: 1, + pageSize: 6, + }, + }, + }, + }); + return; + } const response = await route.fetch({ url: endpoint }); await route.fulfill({ response }); }); diff --git a/e2e/recipe-api.spec.ts b/e2e/recipe-api.spec.ts new file mode 100644 index 0000000..d95fb35 --- /dev/null +++ b/e2e/recipe-api.spec.ts @@ -0,0 +1,170 @@ +import { createServer, type Server } from 'node:http'; +import { randomUUID } from 'node:crypto'; +import { existsSync } from 'node:fs'; +import { readFile } from 'node:fs/promises'; +import { Pool } from 'pg'; +import { expect, test, type BrowserContext, type Page } from '@playwright/test'; +import { createApp } from '../apps/api/src/app.js'; +import { createAuthRepository } from '../apps/api/src/features/auth/authRepository.js'; +import { createAuthService } from '../apps/api/src/features/auth/authService.js'; + +if (existsSync('.env')) process.loadEnvFile('.env'); +test.skip( + !process.env.DATABASE_URL, + 'Requires a development/test PostgreSQL database.', +); + +const schema = 'browser_test_' + randomUUID().replaceAll('-', ''); +let pool: Pool; +let server: Server; +let endpoint: string; + +test.beforeAll(async () => { + pool = new Pool({ + connectionString: process.env.DATABASE_URL, + connectionTimeoutMillis: 5000, + }); + await pool.query(`CREATE SCHEMA "${schema}"`); + const journal = JSON.parse( + await readFile('apps/api/migrations/meta/_journal.json', 'utf8'), + ) as { entries: { tag: string }[] }; + for (const { tag } of journal.entries) { + await pool.query( + (await readFile(`apps/api/migrations/${tag}.sql`, 'utf8')).replaceAll( + '"project2"', + `"${schema}"`, + ), + ); + } + server = createServer( + createApp( + createAuthService(createAuthRepository(pool, pool, schema)), + false, + false, + { pool, schema }, + ), + ); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') + throw new Error('Missing test server address'); + endpoint = `http://127.0.0.1:${address.port}/graphql`; +}); + +test.afterAll(async () => { + if (server) + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ); + if (pool) { + await pool.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); + await pool.end(); + } +}); + +async function connect(context: BrowserContext) { + await context.route('**/project2/api/graphql', async (route) => { + const response = await route.fetch({ url: endpoint }); + await route.fulfill({ response }); + }); +} +async function register(page: Page, email: string) { + await page.goto('register'); + await page.getByLabel(/^Name/).fill('Browser Chef'); + await page.getByLabel(/^Email/).fill(email); + await page.getByLabel(/^Password/).fill('browser-test-password'); + await page.getByLabel(/^Confirm password/).fill('browser-test-password'); + await page.getByRole('button', { name: 'Register', exact: true }).click(); + await expect( + page.getByRole('heading', { name: 'Explore Recipes' }), + ).toBeVisible(); +} + +test('persists create/edit/save/unsave/private/delete flows through the real API', async ({ + page, + context, + browser, +}) => { + test.setTimeout(90000); + await connect(context); + await register(page, 'owner@example.com'); + await page.goto('recipes/new'); + await page.getByLabel(/Recipe title/).fill('Browser soup'); + await page.getByLabel(/Preparation time/).fill('5'); + await page.getByLabel(/Cooking time/).fill('10'); + await page.getByLabel(/Difficulty/).selectOption('medium'); + await page.getByLabel(/Servings/).fill('2'); + await page.getByLabel(/Category/).selectOption('soup'); + await page.getByLabel('Ingredient 1', { exact: true }).fill('Water'); + await page.getByLabel('Ingredient 1 amount').fill('1'); + await page.getByLabel('Ingredient 1 unit').selectOption('l'); + await page.getByLabel('Step 1', { exact: true }).fill('Boil water.'); + await page.getByRole('button', { name: 'Publish recipe' }).click(); + await expect( + page.getByRole('heading', { name: 'Browser soup' }), + ).toBeVisible(); + const recipeUrl = page.url(); + await page.reload(); + await expect( + page.getByRole('heading', { name: 'Browser soup' }), + ).toBeVisible(); + await page.getByRole('link', { name: 'Edit Recipe' }).click(); + await page.getByLabel(/Recipe title/).fill('Edited browser soup'); + await page.getByRole('button', { name: 'Save changes' }).click(); + await expect( + page.getByRole('heading', { name: 'Edited browser soup' }), + ).toBeVisible(); + + const readerContext = await browser.newContext({ + baseURL: 'http://127.0.0.1:4173/project2/', + }); + try { + await connect(readerContext); + const reader = await readerContext.newPage(); + await register(reader, 'reader@example.com'); + await reader.goto(recipeUrl); + await reader.getByRole('button', { name: 'Save to Cookbook' }).click(); + await expect( + reader.getByRole('button', { name: 'Saved', exact: true }), + ).toBeVisible(); + await reader.goto('cookbook?view=saved'); + await expect( + reader.getByRole('link', { name: 'Edited browser soup' }), + ).toBeVisible(); + await reader + .getByRole('button', { + name: 'Remove Edited browser soup from My Cookbook', + }) + .click(); + await reader.getByRole('button', { name: 'Unsave', exact: true }).click(); + await expect( + reader.getByRole('heading', { name: 'No saved recipes yet' }), + ).toBeVisible(); + + await page.getByRole('link', { name: 'Edit Recipe' }).click(); + await page.getByLabel('Private', { exact: true }).check(); + await page.getByRole('button', { name: 'Save changes' }).click(); + await expect( + page.getByRole('heading', { name: 'Edited browser soup' }), + ).toBeVisible(); + await reader.goto(recipeUrl); + await expect( + reader.getByRole('heading', { name: 'Recipe not found' }), + ).toBeVisible(); + await page + .getByRole('button', { name: 'Delete Recipe', exact: true }) + .click(); + await page + .getByRole('button', { name: 'Delete recipe', exact: true }) + .click(); + await expect( + page.getByRole('heading', { name: 'My Cookbook' }), + ).toBeVisible(); + await page.goto(recipeUrl); + await expect( + page.getByRole('heading', { name: 'Recipe not found' }), + ).toBeVisible(); + } finally { + await readerContext.close(); + } +}); diff --git a/e2e/smoke.spec.ts b/e2e/smoke.spec.ts index 08ba89a..56e459a 100644 --- a/e2e/smoke.spec.ts +++ b/e2e/smoke.spec.ts @@ -1,18 +1,66 @@ import { expect, test } from '@playwright/test'; +import type { RecipeFieldsFragment } from '../contracts/generated'; +const recipe: RecipeFieldsFragment = { + id: '11111111-1111-4111-8111-111111111111', + title: 'Creamy salmon pasta', + description: 'Simple pasta', + category: 'dinner', + cuisine: null, + difficulty: 'easy', + visibility: 'public', + imageUrl: null, + sourceRecipeId: null, + prepMinutes: 5, + cookMinutes: 10, + servings: 2, + createdAt: '2026-10-22T12:00:00Z', + updatedAt: '2026-10-22T12:00:00Z', + author: { id: 'chef', name: 'Chef' }, + ingredients: [], + instructions: [], + tags: [], + rating: { average: 0, count: 0 }, + saveCount: 0, + isSaved: false, + isCreatedByCurrentUser: false, +}; // Shell tests run against a static preview, without a backend/database. test.beforeEach(async ({ page }) => { await page.route('**/project2/api/graphql', async (route) => { - const body = route.request().postDataJSON() as { query?: string }; + const body = route.request().postDataJSON() as { + query?: string; + variables?: { id?: string }; + }; if (body.query?.includes('currentUser')) { await route.fulfill({ json: { data: { currentUser: null } } }); - } else await route.continue(); + } else if (body.query?.includes('query Recipes')) { + await route.fulfill({ + json: { + data: { + recipes: { + items: [recipe], + totalCount: 1, + totalPages: 1, + page: 1, + pageSize: 6, + }, + }, + }, + }); + } else { + await route.fulfill({ + json: { + data: { recipe: body.variables?.id === recipe.id ? recipe : null }, + }, + }); + } }); }); const coreRoutes = [ ['/', 'Explore'], - ['/recipes/salmon-pasta', 'Creamy salmon pasta'], + ['/recipes/11111111-1111-4111-8111-111111111111', 'Creamy salmon pasta'], ['/recipes/42', 'Recipe not found'], ['/login', 'Log in'], ['/register', 'Register'], From 4f7dcd70b5ce794baee135a24a4e33f6fe460627 Mon Sep 17 00:00:00 2001 From: "hasan.fawzi" Date: Fri, 23 Oct 2026 15:09:54 +0200 Subject: [PATCH 2/6] feat: add persistent ratings, image uploads and logo favicon --- .dockerignore | 3 +- .env.example | 2 + .gitignore | 1 + apps/api/src/app.ts | 15 +- .../src/features/recipes/imageStorage.test.ts | 83 ++++++ apps/api/src/features/recipes/imageStorage.ts | 103 ++++++++ .../src/features/recipes/recipeRepository.ts | 29 ++ .../src/features/recipes/recipeResolvers.ts | 10 + .../features/recipes/recipeValidation.test.ts | 16 ++ .../src/features/recipes/recipeValidation.ts | 7 +- apps/api/src/generated.ts | 29 +- apps/api/src/schema.graphql | 3 + apps/web/index.html | 1 + apps/web/public/favicon.svg | 8 + .../RecipeRatingInput/RecipeRatingInput.css | 8 +- .../components/recipe/toRecipeCardProps.ts | 3 +- .../recipe-detail/RecipeDetailPage.css | 14 + .../recipe-detail/RecipeDetailPage.test.tsx | 50 +++- .../recipe-detail/RecipeDetailPage.tsx | 109 +++++++- .../recipes/RecipeCreatePage.test.tsx | 2 +- .../src/features/recipes/RecipeCreatePage.tsx | 18 +- .../recipes/RecipeImageField.test.tsx | 36 +++ .../src/features/recipes/RecipeImageField.tsx | 199 ++++++++++++++ apps/web/src/features/recipes/recipeApi.ts | 8 + apps/web/src/features/recipes/recipeImages.ts | 29 ++ apps/web/src/lib/recipeImageUrl.ts | 5 + apps/web/src/test/recipeApiFixtures.ts | 1 + apps/web/src/types/recipe.ts | 1 + apps/web/vite.config.ts | 8 +- compose.dev.yaml | 4 + contracts/generated.ts | 250 ++++++++++++++++++ contracts/operations.graphql | 11 + docs/frontend-integration.md | 37 ++- docs/recipe-api.md | 22 +- e2e/recipe-api.spec.ts | 64 ++++- e2e/smoke.spec.ts | 1 + scripts/test-recipe-api.ts | 106 ++++++++ 37 files changed, 1255 insertions(+), 41 deletions(-) create mode 100644 apps/api/src/features/recipes/imageStorage.test.ts create mode 100644 apps/api/src/features/recipes/imageStorage.ts create mode 100644 apps/web/public/favicon.svg create mode 100644 apps/web/src/features/recipes/RecipeImageField.test.tsx create mode 100644 apps/web/src/features/recipes/RecipeImageField.tsx create mode 100644 apps/web/src/features/recipes/recipeImages.ts create mode 100644 apps/web/src/lib/recipeImageUrl.ts diff --git a/.dockerignore b/.dockerignore index 1c91ad0..14f543d 100644 --- a/.dockerignore +++ b/.dockerignore @@ -10,6 +10,7 @@ dist coverage playwright-report test-results +uploads # Git .git @@ -27,4 +28,4 @@ test-results # Logs *.log -npm-debug.log* \ No newline at end of file +npm-debug.log* diff --git a/.env.example b/.env.example index d3d5ae9..8b81b33 100644 --- a/.env.example +++ b/.env.example @@ -5,3 +5,5 @@ API_PORT=3001 AUTH_TRUST_PROXY=false # false for localhost/current HTTP VM; true when HTTPS is configured. AUTH_COOKIE_SECURE=false +# Optional absolute directory for persisted recipe images (default: uploads/ at project root). +# UPLOAD_DIR=/var/lib/recipe-platform/uploads diff --git a/.gitignore b/.gitignore index a8801f6..007371e 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ coverage/ playwright-report/ test-results/ *.tsbuildinfo +uploads/ diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 0cff506..7417bad 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -1,4 +1,6 @@ import type { Pool } from 'pg'; +import { fileURLToPath } from 'node:url'; +import { handleImageRequest } from './features/recipes/imageStorage.js'; import { db } from './db/client.js'; import { createRecipeRepository } from './features/recipes/recipeRepository.js'; import { createRecipeResolvers } from './features/recipes/recipeResolvers.js'; @@ -24,6 +26,8 @@ export function createApp( trustProxy = process.env.AUTH_TRUST_PROXY === 'true', secureCookie = process.env.AUTH_COOKIE_SECURE === 'true', database: { pool?: Pool; schema?: string } = {}, + uploadDirectory = process.env.UPLOAD_DIR ?? + fileURLToPath(new URL('../../../uploads/', import.meta.url)), ) { const authResolvers = createAuthResolvers(service); const recipes = createRecipeResolvers( @@ -37,7 +41,16 @@ export function createApp( }, plugins: [ { - onRequest({ request, fetchAPI, endResponse }) { + async onRequest({ request, fetchAPI, endResponse }) { + const imageResponse = await handleImageRequest( + request, + service, + uploadDirectory, + ); + if (imageResponse) { + endResponse(imageResponse); + return; + } if ( request.method === 'POST' && (request.headers.get('x-requested-with') !== 'recipe-platform' || diff --git a/apps/api/src/features/recipes/imageStorage.test.ts b/apps/api/src/features/recipes/imageStorage.test.ts new file mode 100644 index 0000000..388548e --- /dev/null +++ b/apps/api/src/features/recipes/imageStorage.test.ts @@ -0,0 +1,83 @@ +import { mkdtemp, readdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { createApp } from '../../app.js'; +import type { AuthService } from '../auth/authService.js'; + +const token = '11111111-1111-4111-8111-111111111111'; +const user = { id: token, name: 'Test Cook', email: 'cook@example.com' }; +const service: AuthService = { + currentUser: async (value) => (value === token ? user : null), + login: async () => ({ user, sessionToken: token }), + register: async () => ({ user, sessionToken: token }), + signOut: async () => true, +}; +// A complete 1x1 PNG, also used to verify bytes survive storage unchanged. +const png = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aOioAAAAASUVORK5CYII=', + 'base64', +); +let directory: string; +beforeAll(async () => { + directory = await mkdtemp(join(tmpdir(), 'recipe-images-')); +}); +afterAll(async () => { + if (directory.startsWith(join(tmpdir(), 'recipe-images-'))) + await rm(directory, { recursive: true, force: true }); +}); +function upload(body: Buffer, headers: Record = {}) { + const app = createApp(service, false, false, {}, directory); + return app.fetch('http://localhost/uploads', { + method: 'POST', + body: new Uint8Array(body), + headers: { + 'Content-Type': 'image/png', + 'X-Requested-With': 'recipe-platform', + Cookie: `t31_project2_session=${token}`, + ...headers, + }, + }); +} + +describe('local image storage', () => { + it('persists an image and serves it after recreating the app', async () => { + const response = await upload(png); + expect(response.status).toBe(201); + const { imageUrl } = (await response.json()) as { imageUrl: string }; + expect(imageUrl).toMatch(/^\/uploads\/[0-9a-f-]+\.png$/); + const restarted = createApp(service, false, false, {}, directory); + const image = await restarted.fetch(`http://localhost${imageUrl}`); + expect(image.status).toBe(200); + expect(image.headers.get('content-type')).toBe('image/png'); + expect(image.headers.get('x-content-type-options')).toBe('nosniff'); + expect(Buffer.from(await image.arrayBuffer())).toEqual(png); + }); + it('requires login and the same custom request header as GraphQL', async () => { + expect((await upload(png, { Cookie: '' })).status).toBe(401); + expect((await upload(png, { 'X-Requested-With': '' })).status).toBe(403); + }); + it('rejects unsupported, spoofed and oversized bodies without writing files', async () => { + const before = await readdir(directory); + expect( + (await upload(png, { 'Content-Type': 'image/svg+xml' })).status, + ).toBe(415); + expect((await upload(Buffer.from(''))).status).toBe( + 415, + ); + expect((await upload(png, { 'Content-Type': 'image/jpeg' })).status).toBe( + 415, + ); + expect((await upload(Buffer.alloc(5 * 1024 * 1024 + 1))).status).toBe(413); + expect(await readdir(directory)).toEqual(before); + }); + it('does not serve arbitrary filenames or missing images', async () => { + const app = createApp(service, false, false, {}, directory); + for (const path of [ + '/uploads/.env', + '/uploads/%2e%2e%2f.env', + '/uploads/11111111-1111-4111-8111-111111111111.jpg', + ]) + expect((await app.fetch('http://localhost' + path)).status).toBe(404); + }); +}); diff --git a/apps/api/src/features/recipes/imageStorage.ts b/apps/api/src/features/recipes/imageStorage.ts new file mode 100644 index 0000000..1ac9e09 --- /dev/null +++ b/apps/api/src/features/recipes/imageStorage.ts @@ -0,0 +1,103 @@ +import { randomUUID } from 'node:crypto'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import type { AuthService } from '../auth/authService.js'; +import { readSessionCookie } from '../auth/sessionCookie.js'; + +const MAX_BYTES = 5 * 1024 * 1024; +const filePattern = + /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}\.(jpg|png|webp)$/; +export const uploadedImagePattern = + /^\/uploads\/[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}\.(jpg|png|webp)$/; +const contentTypes: Record = { + jpg: 'image/jpeg', + png: 'image/png', + webp: 'image/webp', +}; + +function imageExtension(bytes: Buffer) { + if ( + bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) + ) + return 'png'; + if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return 'jpg'; + if ( + bytes.toString('ascii', 0, 4) === 'RIFF' && + bytes.toString('ascii', 8, 12) === 'WEBP' + ) + return 'webp'; + return null; +} + +function failure(status: number, message: string) { + return Response.json({ message }, { status }); +} + +// A single upload endpoint and a restricted file route; client filenames are never used. +export async function handleImageRequest( + request: Request, + service: AuthService, + directory: string, +): Promise { + const path = new URL(request.url).pathname; + if (path !== '/uploads' && !path.startsWith('/uploads/')) return null; + try { + if (request.method === 'GET' && path.startsWith('/uploads/')) { + const filename = path.slice('/uploads/'.length); + if (!filePattern.test(filename)) return failure(404, 'Image not found.'); + try { + const image = await readFile(join(directory, filename)); + return new Response(new Uint8Array(image), { + headers: { + 'Content-Type': contentTypes[filename.split('.').pop()!]!, + 'X-Content-Type-Options': 'nosniff', + }, + }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') + return failure(404, 'Image not found.'); + throw error; + } + } + if (request.method !== 'POST' || path !== '/uploads') + return failure(405, 'Method not allowed.'); + if (request.headers.get('x-requested-with') !== 'recipe-platform') + return failure(403, 'Request blocked.'); + const token = readSessionCookie(request); + if (!token || !(await service.currentUser(token))) + return failure(401, 'Please sign in to upload an image.'); + const type = request.headers.get('content-type')?.split(';')[0]; + if (!type || !Object.values(contentTypes).includes(type)) + return failure(415, 'Choose a JPG, PNG, or WebP image.'); + if (Number(request.headers.get('content-length')) > MAX_BYTES) + return failure(413, 'Choose an image up to 5 MB.'); + const reader = request.body?.getReader(); + if (!reader) return failure(400, 'Choose an image.'); + const chunks: Uint8Array[] = []; + let size = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > MAX_BYTES) { + await reader.cancel(); + return failure(413, 'Choose an image up to 5 MB.'); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + const image = Buffer.concat(chunks); + const extension = imageExtension(image); + if (!extension || contentTypes[extension] !== type) + return failure(415, 'The file must contain a JPG, PNG, or WebP image.'); + await mkdir(directory, { recursive: true }); + const filename = `${randomUUID()}.${extension}`; + await writeFile(join(directory, filename), image, { flag: 'wx' }); + return Response.json({ imageUrl: `/uploads/${filename}` }, { status: 201 }); + } catch { + return failure(500, 'Unable to store the image. Please try again.'); + } +} diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index 617a052..4beff56 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -42,6 +42,7 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved", (SELECT count(*)::int FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id) AS "saveCount", (SELECT json_build_object('average',coalesce(round(avg(score),1),0)::float,'count',count(*)::int) FROM ${t('ratings')} WHERE recipe_id=r.id) AS rating, + (SELECT score FROM ${t('ratings')} WHERE recipe_id=r.id AND user_id=$1::uuid) AS "userRating", coalesce((SELECT json_agg(json_build_object('id',i.id,'name',i.name,'amount',i.amount::float,'unit',i.unit,'note',i.note) ORDER BY i.position) FROM ${t('recipe_ingredients')} i WHERE i.recipe_id=r.id),'[]') AS ingredients, coalesce((SELECT json_agg(json_build_object('step',i.position,'text',i.text) ORDER BY i.position) FROM ${t('recipe_instructions')} i WHERE i.recipe_id=r.id),'[]') AS instructions, coalesce((SELECT json_agg(tag ORDER BY tag) FROM ${t('recipe_tags')} WHERE recipe_id=r.id),'[]') AS tags @@ -224,6 +225,34 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { ); return true; }, + async rate(id: string, score: number, userId: string) { + return transaction(async (client) => { + const result = await client.query( + `SELECT id FROM ${t('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR SHARE`, + [id, userId], + ); + if (!result.rowCount) + throw new GraphQLError( + 'Only public recipes by other users can be rated.', + { + extensions: { code: 'FORBIDDEN' }, + }, + ); + await client.query( + `INSERT INTO ${t('ratings')} (recipe_id,user_id,score) VALUES ($1,$2,$3) + ON CONFLICT (user_id,recipe_id) DO UPDATE SET score=EXCLUDED.score, updated_at=now()`, + [id, userId, score], + ); + return readRequired(client, id, userId); + }); + }, + async removeRating(id: string, userId: string) { + await pool.query( + `DELETE FROM ${t('ratings')} WHERE recipe_id=$1 AND user_id=$2`, + [id, userId], + ); + return true; + }, }; } export type RecipeRepository = ReturnType; diff --git a/apps/api/src/features/recipes/recipeResolvers.ts b/apps/api/src/features/recipes/recipeResolvers.ts index f45e485..044fcc1 100644 --- a/apps/api/src/features/recipes/recipeResolvers.ts +++ b/apps/api/src/features/recipes/recipeResolvers.ts @@ -35,6 +35,16 @@ export function createRecipeResolvers(repository: RecipeRepository) { ), }, Mutation: { + rateRecipe: (_parent, args, context) => { + const userId = requireUser(context); + return repository.rate( + recipeId(args.id), + validate(z.number().int().min(1).max(5), args.score), + userId, + ); + }, + removeRecipeRating: (_parent, args, context) => + repository.removeRating(recipeId(args.id), requireUser(context)), createRecipe: (_parent, args, context) => { const userId = requireUser(context); return repository.create( diff --git a/apps/api/src/features/recipes/recipeValidation.test.ts b/apps/api/src/features/recipes/recipeValidation.test.ts index 9825a7c..e874b52 100644 --- a/apps/api/src/features/recipes/recipeValidation.test.ts +++ b/apps/api/src/features/recipes/recipeValidation.test.ts @@ -46,4 +46,20 @@ describe('recipe validation', () => { }); expect(() => validate(listInputSchema, { pageSize: 51 })).toThrow(); }); + it('accepts only generated local image paths or HTTP(S) URLs', () => { + const imageUrl = '/uploads/11111111-1111-4111-8111-111111111111.jpg'; + expect(validate(recipeInputSchema, { ...input, imageUrl }).imageUrl).toBe( + imageUrl, + ); + for (const invalid of [ + '/uploads/../.env', + '/uploads/test.svg', + '//other.example/file.jpg', + 'blob:local-preview', + ]) { + expect(() => + validate(recipeInputSchema, { ...input, imageUrl: invalid }), + ).toThrow(); + } + }); }); diff --git a/apps/api/src/features/recipes/recipeValidation.ts b/apps/api/src/features/recipes/recipeValidation.ts index b98f118..89e022a 100644 --- a/apps/api/src/features/recipes/recipeValidation.ts +++ b/apps/api/src/features/recipes/recipeValidation.ts @@ -1,5 +1,6 @@ import { GraphQLError } from 'graphql'; import { z } from 'zod'; +import { uploadedImagePattern } from './imageStorage.js'; export const categorySchema = z.enum([ 'breakfast', @@ -18,8 +19,10 @@ export const recipeInputSchema = z.object({ title: z.string().trim().min(1).max(160), description: z.string().trim().max(200), imageUrl: z - .url({ protocol: /^https?$/ }) - .max(2048) + .union([ + z.url({ protocol: /^https?$/ }).max(2048), + z.string().regex(uploadedImagePattern), + ]) .nullish() .transform((value) => value ?? null), category: categorySchema, diff --git a/apps/api/src/generated.ts b/apps/api/src/generated.ts index 1e42561..b7d2fec 100644 --- a/apps/api/src/generated.ts +++ b/apps/api/src/generated.ts @@ -68,6 +68,8 @@ export type Mutation = { deleteRecipe: Scalars['Boolean']['output']; saveRecipe: Recipe; unsaveRecipe: Scalars['Boolean']['output']; + rateRecipe: Recipe; + removeRecipeRating: Scalars['Boolean']['output']; register: AuthPayload; login: AuthPayload; signOut: Scalars['Boolean']['output']; @@ -94,6 +96,15 @@ export type MutationUnsaveRecipeArgs = { id: Scalars['ID']['input']; }; +export type MutationRateRecipeArgs = { + id: Scalars['ID']['input']; + score: Scalars['Int']['input']; +}; + +export type MutationRemoveRecipeRatingArgs = { + id: Scalars['ID']['input']; +}; + export type MutationRegisterArgs = { name: Scalars['String']['input']; email: Scalars['String']['input']; @@ -153,6 +164,7 @@ export type Recipe = { instructions: Array; tags: Array; rating: RatingSummary; + userRating?: Maybe; saveCount: Scalars['Int']['output']; isSaved: Scalars['Boolean']['output']; isCreatedByCurrentUser: Scalars['Boolean']['output']; @@ -328,11 +340,11 @@ export type ResolversTypes = { Query: ResolverTypeWrapper>; Mutation: ResolverTypeWrapper>; Boolean: ResolverTypeWrapper; + Int: ResolverTypeWrapper; RecipeAuthor: ResolverTypeWrapper; Ingredient: ResolverTypeWrapper; Float: ResolverTypeWrapper; Instruction: ResolverTypeWrapper; - Int: ResolverTypeWrapper; RatingSummary: ResolverTypeWrapper; Recipe: ResolverTypeWrapper; RecipePage: ResolverTypeWrapper; @@ -350,11 +362,11 @@ export type ResolversParentTypes = { Query: Record; Mutation: Record; Boolean: Scalars['Boolean']['output']; + Int: Scalars['Int']['output']; RecipeAuthor: RecipeAuthor; Ingredient: Ingredient; Float: Scalars['Float']['output']; Instruction: Instruction; - Int: Scalars['Int']['output']; RatingSummary: RatingSummary; Recipe: Recipe; RecipePage: RecipePage; @@ -447,6 +459,18 @@ export type MutationResolvers< ContextType, RequireFields >; + rateRecipe?: Resolver< + ResolversTypes['Recipe'], + ParentType, + ContextType, + RequireFields + >; + removeRecipeRating?: Resolver< + ResolversTypes['Boolean'], + ParentType, + ContextType, + RequireFields + >; register?: Resolver< ResolversTypes['AuthPayload'], ParentType, @@ -549,6 +573,7 @@ export type RecipeResolvers< >; tags?: Resolver, ParentType, ContextType>; rating?: Resolver; + userRating?: Resolver, ParentType, ContextType>; saveCount?: Resolver; isSaved?: Resolver; isCreatedByCurrentUser?: Resolver< diff --git a/apps/api/src/schema.graphql b/apps/api/src/schema.graphql index 8825478..68fd67a 100644 --- a/apps/api/src/schema.graphql +++ b/apps/api/src/schema.graphql @@ -47,6 +47,8 @@ type Mutation { deleteRecipe(id: ID!): Boolean! saveRecipe(id: ID!): Recipe! unsaveRecipe(id: ID!): Boolean! + rateRecipe(id: ID!, score: Int!): Recipe! + removeRecipeRating(id: ID!): Boolean! register(name: String!, email: String!, password: String!): AuthPayload! login(email: String!, password: String!): AuthPayload! signOut: Boolean! @@ -91,6 +93,7 @@ type Recipe { instructions: [Instruction!]! tags: [String!]! rating: RatingSummary! + userRating: Int saveCount: Int! isSaved: Boolean! isCreatedByCurrentUser: Boolean! diff --git a/apps/web/index.html b/apps/web/index.html index 98d93bf..ca7696e 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -3,6 +3,7 @@ + Recipe Platform diff --git a/apps/web/public/favicon.svg b/apps/web/public/favicon.svg new file mode 100644 index 0000000..955188c --- /dev/null +++ b/apps/web/public/favicon.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/apps/web/src/components/recipe/RecipeRatingInput/RecipeRatingInput.css b/apps/web/src/components/recipe/RecipeRatingInput/RecipeRatingInput.css index 02572d3..d75261d 100644 --- a/apps/web/src/components/recipe/RecipeRatingInput/RecipeRatingInput.css +++ b/apps/web/src/components/recipe/RecipeRatingInput/RecipeRatingInput.css @@ -65,12 +65,14 @@ .recipe-rating-input__control { position: absolute; + inset: 0; - width: 1px; - height: 1px; + width: 100%; + height: 100%; + margin: 0; opacity: 0; - pointer-events: none; + cursor: inherit; } .recipe-rating-input__star { diff --git a/apps/web/src/components/recipe/toRecipeCardProps.ts b/apps/web/src/components/recipe/toRecipeCardProps.ts index af3dc80..d18cf65 100644 --- a/apps/web/src/components/recipe/toRecipeCardProps.ts +++ b/apps/web/src/components/recipe/toRecipeCardProps.ts @@ -1,5 +1,6 @@ import type { Recipe } from '../../types/recipe'; import type { RecipeCardProps } from './RecipeCard/RecipeCard'; +import { recipeImageUrl } from '../../lib/recipeImageUrl'; function formatTagLabel(tag: string) { return tag @@ -30,7 +31,7 @@ export function toRecipeCardProps(recipe: Recipe): RecipeCardProps { return { ...commonProps, - imageSrc: recipe.imageUrl, + imageSrc: recipeImageUrl(recipe.imageUrl), imageAlt: recipe.title, }; } diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.css b/apps/web/src/features/recipe-detail/RecipeDetailPage.css index 7188470..059b14d 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.css +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.css @@ -1,4 +1,18 @@ @layer components { + .recipe-detail-page__rating-trigger { + padding: 0; + border: 0; + background: transparent; + color: inherit; + cursor: pointer; + border-radius: var(--radius-md); + } + + .recipe-detail-page__rating-trigger:focus-visible { + outline: var(--border-width-medium) solid var(--color-focus-ring); + outline-offset: 4px; + } + .recipe-detail-page { display: flex; flex-direction: column; diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx index 945de33..f90b9fa 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx @@ -1,4 +1,4 @@ -import { render, screen } from '@testing-library/react'; +import { render, screen, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; @@ -38,8 +38,7 @@ it('loads details and scales ingredient quantities without changing the server', .setup() .click(screen.getAllByRole('button', { name: 'Increase servings' })[0]!); expect(screen.getByText('1.5 l')).toBeTruthy(); - expect(screen.queryByRole('button', { name: 'Rate Recipe' })).toBeNull(); - expect(screen.getByText('Rating recipes is not available yet.')).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Rate Recipe' })).toBeTruthy(); }); it('treats inaccessible private recipes as unavailable', async () => { mockRecipeFetch(() => ({ data: { recipe: null } })); @@ -95,3 +94,48 @@ it('handles malformed recipe IDs as not found without an API request', async () ).toBeTruthy(); expect(fetch).not.toHaveBeenCalled(); }); + +it('keeps a failed rating editable and refreshes the persisted rating after retry', async () => { + let score: number | null = null; + let fail = true; + mockRecipeFetch((operation, variables) => { + if (operation === 'RateRecipe') { + if (fail) return { errors: [{ extensions: { code: 'FORBIDDEN' } }] }; + score = Number(variables.score); + return { data: { rateRecipe: { ...apiRecipe, userRating: score } } }; + } + if (operation === 'RemoveRecipeRating') { + score = null; + return { data: { removeRecipeRating: true } }; + } + return { data: { recipe: { ...apiRecipe, userRating: score } } }; + }); + mount(); + const user = userEvent.setup(); + await user.click( + await screen.findByRole('button', { name: 'Rate this recipe' }), + ); + await user.click(screen.getByRole('radio', { name: '4 stars' })); + await user.click(screen.getByRole('button', { name: 'Save rating' })); + const dialog = within( + screen.getByRole('dialog', { name: 'Rate this recipe' }), + ); + expect( + await dialog.findByText( + 'You do not have permission to perform this action.', + ), + ).toBeTruthy(); + expect( + (dialog.getByRole('radio', { name: '4 stars' }) as HTMLInputElement) + .checked, + ).toBe(true); + fail = false; + await user.click(dialog.getByRole('button', { name: 'Save rating' })); + await user.click( + await screen.findByRole('button', { name: 'Your rating: 4/5' }), + ); + await user.click(screen.getByRole('button', { name: 'Remove rating' })); + expect( + await screen.findByRole('button', { name: 'Rate Recipe' }), + ).toBeTruthy(); +}); diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx index bdc8bd8..71ef56c 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx @@ -5,6 +5,9 @@ import { useLocation, useNavigate, useParams } from 'react-router-dom'; import fallbackRecipeImage from '../../assets/recipe-fallback.png'; import RecipeMeta from '../../components/recipe/RecipeMeta/RecipeMeta'; import RecipeRating from '../../components/recipe/RecipeRating/RecipeRating'; +import RecipeRatingInput from '../../components/recipe/RecipeRatingInput/RecipeRatingInput'; +import Dialog from '../../components/ui/Dialog/Dialog'; +import { recipeImageUrl } from '../../lib/recipeImageUrl'; import Avatar from '../../components/ui/Avatar/Avatar'; import Button from '../../components/ui/Button/Button'; import ConfirmationDialog from '../../components/ui/ConfirmationDialog/ConfirmationDialog'; @@ -27,6 +30,7 @@ import type { Recipe } from '../../types/recipe'; import { changeRecipeSaved, + changeRecipeRating, deleteRecipe, getRecipe, recipeErrorMessage, @@ -102,6 +106,8 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { const [confirmUnsaveOpen, setConfirmUnsaveOpen] = useState(false); const [feedback, setFeedback] = useState(null); const [showAllTags, setShowAllTags] = useState(false); + const [ratingOpen, setRatingOpen] = useState(false); + const [pendingRating, setPendingRating] = useState(recipe.userRating ?? 0); const isOwner = recipe.isCreatedByCurrentUser; const isPrivate = recipe.visibility === 'private'; @@ -162,10 +168,16 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { }); } + function openRating() { + setPendingRating(recipe.userRating ?? 0); + setRatingOpen(true); + } + async function performAction(action: () => Promise, message: string) { if (busyRef.current) return; busyRef.current = true; setBusy(true); + setFeedback(null); try { await action(); setFeedback({ tone: 'success', title: 'Recipe updated', message }); @@ -239,7 +251,11 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { ] .filter(Boolean) .join(' ')} - src={recipe.imageUrl ?? fallbackRecipeImage} + src={ + recipe.imageUrl + ? recipeImageUrl(recipe.imageUrl) + : fallbackRecipeImage + } alt={recipe.imageUrl ? recipe.title : ''} /> @@ -273,10 +289,31 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { {!isPrivate ? ( - + canSaveOrRate ? ( + + ) : ( +
+ + + {isOwner + ? 'You cannot rate your own recipe.' + : 'Sign in to rate this recipe.'} + +
+ ) ) : null} @@ -373,7 +410,15 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { {isSaved ? 'Saved' : 'Save to Cookbook'} -

Rating recipes is not available yet.

+ ) : null} @@ -579,6 +624,58 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { > This action cannot be undone. + { + if (!busy) setRatingOpen(false); + }} + footer={ + <> + {recipe.userRating != null && ( + + )} + + + + } + > +
+ +
+ {feedback?.tone === 'error' &&

{feedback.message}

} +
{feedback ? (
{ expect( screen.getByRole('group', { name: /Visibility/ }), ).toBeInTheDocument(); - expect(screen.queryByLabelText(/Recipe image/)).not.toBeInTheDocument(); + expect(screen.getByLabelText('Recipe image')).toBeInTheDocument(); expect(screen.getByLabelText(/Preparation time/)).toBeInTheDocument(); expect(screen.getByLabelText(/Difficulty/)).toBeInTheDocument(); }); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index 09d73e2..57d82be 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -28,6 +28,7 @@ import { import { useRecipeQuery } from './useRecipeQuery'; import RecipeQueryStatus from './RecipeQueryStatus'; import LinkButton from '../../components/ui/LinkButton/LinkButton'; +import RecipeImageField from './RecipeImageField'; import './RecipeCreatePage.css'; @@ -73,6 +74,8 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { const busyRef = useRef(false); const [pending, setPending] = useState(false); const [submitError, setSubmitError] = useState(''); + const [imageUrl, setImageUrl] = useState(recipe?.imageUrl ?? null); + const [imagePending, setImagePending] = useState(false); const [title, setTitle] = useState(recipe?.title ?? ''); const [description, setDescription] = useState(recipe?.description ?? ''); const [cookingTime, setCookingTime] = useState( @@ -358,7 +361,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { async function handleSubmit(event: FormEvent) { event.preventDefault(); - if (busyRef.current) return; + if (busyRef.current || imagePending) return; const nextErrors = validateForm(); setErrors(nextErrors); @@ -422,7 +425,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { .split(',') .map((tag) => tag.trim()) .filter(Boolean), - imageUrl: recipe?.imageUrl ?? null, + imageUrl, cuisine: recipe?.cuisine || null, }; const saved = await writeRecipe(input, recipe?.id); @@ -512,10 +515,11 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
-

- Image uploads are not available yet. Existing recipe images are - kept when editing. -

+
Save draft - diff --git a/apps/web/src/features/recipes/RecipeImageField.test.tsx b/apps/web/src/features/recipes/RecipeImageField.test.tsx new file mode 100644 index 0000000..c5f289a --- /dev/null +++ b/apps/web/src/features/recipes/RecipeImageField.test.tsx @@ -0,0 +1,36 @@ +import { fireEvent, render, screen } from '@testing-library/react'; +import { expect, it, vi } from 'vitest'; +import RecipeImageField from './RecipeImageField'; + +it('rejects unsupported or oversized images before uploading', () => { + const onChange = vi.fn(); + const pending = vi.fn(); + render( + , + ); + const input = screen.getByLabelText('Recipe image'); + fireEvent.change(input, { + target: { + files: [new File(['bad'], 'bad.svg', { type: 'image/svg+xml' })], + }, + }); + expect(screen.getByRole('alert').textContent).toContain( + 'Choose a JPG, PNG, or WebP image.', + ); + fireEvent.change(input, { + target: { + files: [ + new File([new Uint8Array(5 * 1024 * 1024 + 1)], 'large.png', { + type: 'image/png', + }), + ], + }, + }); + expect(screen.getByRole('alert').textContent).toContain('up to 5 MB'); + expect(onChange).not.toHaveBeenCalled(); + expect(pending).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/features/recipes/RecipeImageField.tsx b/apps/web/src/features/recipes/RecipeImageField.tsx new file mode 100644 index 0000000..5e46008 --- /dev/null +++ b/apps/web/src/features/recipes/RecipeImageField.tsx @@ -0,0 +1,199 @@ +import { useEffect, useState } from 'react'; +import Cropper, { type Area } from 'react-easy-crop'; +import Button from '../../components/ui/Button/Button'; +import Dialog from '../../components/ui/Dialog/Dialog'; +import { recipeImageUrl } from '../../lib/recipeImageUrl'; +import { uploadRecipeImage } from './recipeImages'; + +async function cropImage(url: string, area: Area): Promise { + const image = new Image(); + image.src = url; + await new Promise((resolve, reject) => { + image.onload = () => resolve(); + image.onerror = () => reject(new Error('Unable to read this image.')); + }); + const canvas = document.createElement('canvas'); + canvas.width = area.width; + canvas.height = area.height; + const context = canvas.getContext('2d'); + if (!context) throw new Error('Unable to crop this image.'); + context.fillStyle = '#ffffff'; + context.fillRect(0, 0, canvas.width, canvas.height); + context.drawImage( + image, + area.x, + area.y, + area.width, + area.height, + 0, + 0, + canvas.width, + canvas.height, + ); + return new Promise((resolve, reject) => + canvas.toBlob( + (blob) => + blob ? resolve(blob) : reject(new Error('Unable to crop this image.')), + 'image/jpeg', + 0.9, + ), + ); +} + +export default function RecipeImageField({ + value, + onChange, + onPendingChange, +}: { + value: string | null; + onChange: (url: string | null) => void; + onPendingChange: (pending: boolean) => void; +}) { + const [source, setSource] = useState(''); + const [crop, setCrop] = useState({ x: 0, y: 0 }); + const [zoom, setZoom] = useState(1); + const [area, setArea] = useState(); + const [uploading, setUploading] = useState(false); + const [error, setError] = useState(''); + useEffect( + () => () => { + if (source) URL.revokeObjectURL(source); + }, + [source], + ); + + function chooseImage(file?: File) { + setError(''); + if (!file) return; + if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) { + setError('Choose a JPG, PNG, or WebP image.'); + return; + } + if (file.size > 5 * 1024 * 1024) { + setError('Choose an image up to 5 MB.'); + return; + } + setCrop({ x: 0, y: 0 }); + setZoom(1); + setArea(undefined); + setSource(URL.createObjectURL(file)); + onPendingChange(true); + } + function cancel() { + if (!uploading) { + setSource(''); + setError(''); + onPendingChange(false); + } + } + async function upload() { + if (!area || uploading) return; + setUploading(true); + setError(''); + try { + onChange(await uploadRecipeImage(await cropImage(source, area))); + setSource(''); + onPendingChange(false); + } catch (error) { + setError( + error instanceof Error ? error.message : 'Unable to upload image.', + ); + } finally { + setUploading(false); + } + } + + return ( +
+ {value && ( +
+ Recipe preview + +
+ )} + + { + chooseImage(event.target.files?.[0]); + event.target.value = ''; + }} + /> +

+ JPG, PNG or WebP, up to 5 MB. Crop your image before uploading. +

+ {error && !source &&

{error}

} + + + + + } + > +
+ {source && ( + setArea(nextArea)} + mediaProps={{ + onError: () => + setError('Unable to read this image. Choose another file.'), + }} + /> + )} +
+ + {error &&

{error}

} +
+
+ ); +} diff --git a/apps/web/src/features/recipes/recipeApi.ts b/apps/web/src/features/recipes/recipeApi.ts index 48dd77c..ecbfd8e 100644 --- a/apps/web/src/features/recipes/recipeApi.ts +++ b/apps/web/src/features/recipes/recipeApi.ts @@ -9,6 +9,8 @@ import { DeleteRecipeDocument, SaveRecipeDocument, UnsaveRecipeDocument, + RateRecipeDocument, + RemoveRecipeRatingDocument, type RecipeFieldsFragment, type RecipeInput, type RecipeListInput, @@ -76,6 +78,12 @@ export async function changeRecipeSaved(id: string, saved: boolean) { invalidateRecipes(); } +export async function changeRecipeRating(id: string, score: number | null) { + if (score === null) await graphqlRequest(RemoveRecipeRatingDocument, { id }); + else await graphqlRequest(RateRecipeDocument, { id, score }); + invalidateRecipes(); +} + export function recipeErrorMessage(error: unknown) { if (error instanceof ApiError) { const messages: Record = { diff --git a/apps/web/src/features/recipes/recipeImages.ts b/apps/web/src/features/recipes/recipeImages.ts new file mode 100644 index 0000000..bb9716e --- /dev/null +++ b/apps/web/src/features/recipes/recipeImages.ts @@ -0,0 +1,29 @@ +export async function uploadRecipeImage(image: Blob): Promise { + if (image.size > 5 * 1024 * 1024) + throw new Error('Choose an image up to 5 MB.'); + const response = await fetch( + import.meta.env.DEV ? '/uploads' : '/project2/api/uploads', + { + method: 'POST', + credentials: 'same-origin', + headers: { + 'Content-Type': image.type, + 'X-Requested-With': 'recipe-platform', + }, + body: image, + }, + ); + if (!response.ok) { + const messages: Record = { + 401: 'Please sign in to upload an image.', + 413: 'Choose an image up to 5 MB.', + 415: 'Choose a valid JPG, PNG, or WebP image.', + }; + throw new Error( + messages[response.status] ?? + 'Unable to upload the image. Please try again.', + ); + } + const result: { imageUrl: string } = await response.json(); + return result.imageUrl; +} diff --git a/apps/web/src/lib/recipeImageUrl.ts b/apps/web/src/lib/recipeImageUrl.ts new file mode 100644 index 0000000..64e6a01 --- /dev/null +++ b/apps/web/src/lib/recipeImageUrl.ts @@ -0,0 +1,5 @@ +export function recipeImageUrl(url: string) { + return url.startsWith('/uploads/') && !import.meta.env.DEV + ? `/project2/api${url}` + : url; +} diff --git a/apps/web/src/test/recipeApiFixtures.ts b/apps/web/src/test/recipeApiFixtures.ts index 539168c..814d033 100644 --- a/apps/web/src/test/recipeApiFixtures.ts +++ b/apps/web/src/test/recipeApiFixtures.ts @@ -23,6 +23,7 @@ export const apiRecipe: RecipeFieldsFragment = { instructions: [{ step: 1, text: 'Boil the water.' }], tags: ['quick'], rating: { average: 4, count: 2 }, + userRating: null, saveCount: 0, isSaved: false, isCreatedByCurrentUser: false, diff --git a/apps/web/src/types/recipe.ts b/apps/web/src/types/recipe.ts index 4d7f1a0..237fbe5 100644 --- a/apps/web/src/types/recipe.ts +++ b/apps/web/src/types/recipe.ts @@ -47,6 +47,7 @@ export interface Recipe { ingredients: Ingredient[]; instructions: RecipeInstruction[]; rating: RatingSummary; + userRating?: number | null; saveCount: number; visibility: RecipeVisibility; isSaved: boolean; diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 424f5cd..44b5a17 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -4,5 +4,11 @@ import { defineConfig } from 'vite'; export default defineConfig({ base: '/project2/', plugins: [react()], - server: { proxy: { '/graphql': 'http://127.0.0.1:3001' } }, + server: { + watch: { usePolling: process.env.CHOKIDAR_USEPOLLING === 'true' }, + proxy: { + '/graphql': 'http://127.0.0.1:3001', + '/uploads': 'http://127.0.0.1:3001', + }, + }, }); diff --git a/compose.dev.yaml b/compose.dev.yaml index 1cc1a14..792e4fe 100644 --- a/compose.dev.yaml +++ b/compose.dev.yaml @@ -35,6 +35,8 @@ services: # The API must listen outside the container's loopback interface. API_HOST: 0.0.0.0 API_PORT: 3001 + # Detect source edits reliably through Windows bind mounts. + CHOKIDAR_USEPOLLING: 'true' ports: - '5173:5173' @@ -46,9 +48,11 @@ services: # Keep container node_modules separate from the host. - node_modules:/app/node_modules + - recipe_images:/app/uploads init: true volumes: postgres_data: node_modules: + recipe_images: diff --git a/contracts/generated.ts b/contracts/generated.ts index 25c9a17..eb3cdf7 100644 --- a/contracts/generated.ts +++ b/contracts/generated.ts @@ -101,6 +101,7 @@ export type RecipeFieldsFragment = { createdAt: string; updatedAt: string; tags: Array; + userRating: number | null; saveCount: number; isSaved: boolean; isCreatedByCurrentUser: boolean; @@ -142,6 +143,7 @@ export type RecipesQuery = { createdAt: string; updatedAt: string; tags: Array; + userRating: number | null; saveCount: number; isSaved: boolean; isCreatedByCurrentUser: boolean; @@ -180,6 +182,7 @@ export type RecipeQuery = { createdAt: string; updatedAt: string; tags: Array; + userRating: number | null; saveCount: number; isSaved: boolean; isCreatedByCurrentUser: boolean; @@ -223,6 +226,7 @@ export type CookbookQuery = { createdAt: string; updatedAt: string; tags: Array; + userRating: number | null; saveCount: number; isSaved: boolean; isCreatedByCurrentUser: boolean; @@ -261,6 +265,7 @@ export type CreateRecipeMutation = { createdAt: string; updatedAt: string; tags: Array; + userRating: number | null; saveCount: number; isSaved: boolean; isCreatedByCurrentUser: boolean; @@ -299,6 +304,7 @@ export type UpdateRecipeMutation = { createdAt: string; updatedAt: string; tags: Array; + userRating: number | null; saveCount: number; isSaved: boolean; isCreatedByCurrentUser: boolean; @@ -342,6 +348,7 @@ export type SaveRecipeMutation = { createdAt: string; updatedAt: string; tags: Array; + userRating: number | null; saveCount: number; isSaved: boolean; isCreatedByCurrentUser: boolean; @@ -364,6 +371,51 @@ export type UnsaveRecipeMutationVariables = Exact<{ export type UnsaveRecipeMutation = { unsaveRecipe: boolean }; +export type RateRecipeMutationVariables = Exact<{ + id: string | number; + score: number; +}>; + +export type RateRecipeMutation = { + rateRecipe: { + id: string; + title: string; + description: string; + category: RecipeCategory; + cuisine: string | null; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + userRating: number | null; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + }; +}; + +export type RemoveRecipeRatingMutationVariables = Exact<{ + id: string | number; +}>; + +export type RemoveRecipeRatingMutation = { removeRecipeRating: boolean }; + export const RecipeFieldsFragmentDoc = { kind: 'Document', definitions: [ @@ -439,6 +491,7 @@ export const RecipeFieldsFragmentDoc = { ], }, }, + { kind: 'Field', name: { kind: 'Name', value: 'userRating' } }, { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, { @@ -830,6 +883,7 @@ export const RecipesDocument = { ], }, }, + { kind: 'Field', name: { kind: 'Name', value: 'userRating' } }, { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, { @@ -959,6 +1013,7 @@ export const RecipeDocument = { ], }, }, + { kind: 'Field', name: { kind: 'Name', value: 'userRating' } }, { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, { @@ -1123,6 +1178,7 @@ export const CookbookDocument = { ], }, }, + { kind: 'Field', name: { kind: 'Name', value: 'userRating' } }, { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, { @@ -1258,6 +1314,7 @@ export const CreateRecipeDocument = { ], }, }, + { kind: 'Field', name: { kind: 'Name', value: 'userRating' } }, { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, { @@ -1412,6 +1469,7 @@ export const UpdateRecipeDocument = { ], }, }, + { kind: 'Field', name: { kind: 'Name', value: 'userRating' } }, { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, { @@ -1586,6 +1644,7 @@ export const SaveRecipeDocument = { ], }, }, + { kind: 'Field', name: { kind: 'Name', value: 'userRating' } }, { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, { @@ -1639,3 +1698,194 @@ export const UnsaveRecipeDocument = { UnsaveRecipeMutation, UnsaveRecipeMutationVariables >; +export const RateRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'RateRecipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, + }, + }, + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'score' }, + }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'Int' } }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'rateRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + { + kind: 'Argument', + name: { kind: 'Name', value: 'score' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'score' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'userRating' } }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; +export const RemoveRecipeRatingDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'RemoveRecipeRating' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'removeRecipeRating' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + }, + ], + }, + }, + ], +} as unknown as DocumentNode< + RemoveRecipeRatingMutation, + RemoveRecipeRatingMutationVariables +>; diff --git a/contracts/operations.graphql b/contracts/operations.graphql index 974ac34..ebfb9a9 100644 --- a/contracts/operations.graphql +++ b/contracts/operations.graphql @@ -69,6 +69,7 @@ fragment RecipeFields on Recipe { average count } + userRating saveCount isSaved isCreatedByCurrentUser @@ -121,3 +122,13 @@ mutation SaveRecipe($id: ID!) { mutation UnsaveRecipe($id: ID!) { unsaveRecipe(id: $id) } + +mutation RateRecipe($id: ID!, $score: Int!) { + rateRecipe(id: $id, score: $score) { + ...RecipeFields + } +} + +mutation RemoveRecipeRating($id: ID!) { + removeRecipeRating(id: $id) +} diff --git a/docs/frontend-integration.md b/docs/frontend-integration.md index 437d602..16ad844 100644 --- a/docs/frontend-integration.md +++ b/docs/frontend-integration.md @@ -16,7 +16,8 @@ - [x] Delete owned recipes after confirmation. - [x] Handle loading, empty, unavailable and retryable error states separately. - [x] Keep form data after failed mutations and prevent duplicate submissions. -- [x] Temporarily hide image uploads/cropping and disable rating actions. +- [x] Upload/crop JPG, PNG and WebP images to persistent server storage. +- [x] Create, update and remove the current user's persisted rating. - [x] Replace mock-page assertions with API integration tests. - [x] Add a real API/PostgreSQL browser test for recipe CRUD and Save/Unsave. @@ -37,11 +38,41 @@ remain available. - [ ] Add ingredient/tag search and agree on normalization rules in D3. - [ ] Implement additional sorting in the backend before pagination. - [ ] Define trending behavior independently of the old fixed mock date. -- [ ] Add image storage/uploading that returns durable URLs to recipe CRUD. -- [ ] Add persistent rating mutations before enabling rating controls. - [ ] Consider separate SQL summary/detail reads and domain-error translation. - [ ] Verify the deployed VM flow after merge and deployment. The draft button keeps edits in the current form only. Drafts are not persisted across navigation or reload. Mock query modules remain solely for prototype tests and are not imported by production pages. + +## Local rating and image checks + +Start with `docker compose -f compose.dev.yaml up --build`, then open +`http://localhost:5173/project2/`. Alternatively, use `npm run dev` with a +configured PostgreSQL database and open `http://127.0.0.1:5173/project2/`. + +1. Create a recipe, select a JPG/PNG/WebP image up to 5 MB, adjust the crop, + click **Use image**, then publish. Reload to check that the image remains. +2. Edit the recipe to replace or remove its image, save and reload. +3. Sign in with a second account. Open the first account's public recipe, + click **Rate Recipe**, select stars and save. Reload to check persistence. +4. Change the rating and verify it replaces the earlier score. Remove the + rating and verify that the count/average update. +5. Confirm that logged-out users cannot rate or upload, and that users cannot + rate their own or private recipes. + +Ratings use the existing table; no database migration is needed. Each user has +at most one rating per recipe. Removing a rating affects only that user's row. + +The API accepts authenticated binary uploads at `/uploads` and serves generated +file paths under `/uploads/`. Vite proxies these paths locally. In deployment, +the frontend uses `/project2/api/uploads`; the Apache proxy must forward this +path to the API's `/uploads` path as well as forwarding `/graphql`. + +Images default to `uploads/` at the project root (excluded from Git). Set the +absolute `UPLOAD_DIR` for a different persistent directory and make it writable +by the API process. Docker uses the `recipe_images` volume, preserved by +`docker compose down` and container rebuilds. Keep this volume/directory when +deploying. Image URLs are publicly readable; private recipe access does not +make image files private. Removing/replacing a recipe image changes its URL +reference; old files are retained rather than automatically deleted. diff --git a/docs/recipe-api.md b/docs/recipe-api.md index d555956..ec265b1 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -144,8 +144,9 @@ E-post og passordhash eksponeres ikke som oppskriftsforfatterdata. `RecipeInput` inneholder tittel, beskrivelse, kategori, difficulty, visibility, prepMinutes, cookMinutes, servings, ingredients, instructions og tags. -`cuisine` og `imageUrl` er valgfrie. Bildet må være en HTTP(S)-URL; dette API-et -laster ikke opp bildefiler. En ingrediens har name, amount, unit og valgfri note. +`cuisine` og `imageUrl` er valgfrie. Bildet kan være en HTTP(S)-URL eller en +generert `/uploads/.`-sti fra bildeopplastingen. En ingrediens +har name, amount, unit og valgfri note. Instruksjoner sendes som en liste strenger; rekkefølgen bestemmer step/position. Minst én ingrediens og ett steg kreves. Mengder må være positive med maksimalt @@ -188,10 +189,15 @@ ukjente oppskrifter gir samme feil og avslører ikke private data. «recently updated» er ikke det samme som opprettelsesdato. Flere sorteringer skal implementeres i backend før LIMIT/OFFSET, med stabil tie-breaker og tester over flere sider. Ikke sorter eller filtrer én hentet side lokalt. -- Midlertidig opprettes oppskrifter uten opplastede bilder. Filvalg og - beskjæring er skjult med en tydelig forklaring. Ikke send - lokale blob-/data-URL-er som imageUrl. Senere kan en separat opplastingstjeneste - returnere en varig HTTP(S)-URL til eksisterende CRUD-input. +- Innloggede brukere kan velge og beskjære bilder før opplasting. API-et tar + imot JPG, PNG og WebP opptil 5 MB på `/uploads` og returnerer en generert sti. + Ikke send lokale blob-/data-URL-er som imageUrl. Se lagring og lokal testløype + i [frontend integration checklist](frontend-integration.md). +- `rateRecipe(id, score)` krever innlogging og score 1–5. Bare offentlige + oppskrifter av andre brukere kan vurderes. Ny score erstatter egen tidligere + vurdering. `removeRecipeRating(id)` fjerner bare egen vurdering og er + idempotent. `userRating` er brukerens egen score eller null; `rating` er + oppsummert gjennomsnitt og antall. Ingen ny migrasjon er nødvendig. - Frontendintegrasjonen ligger i en egen branch etter API-endringene. Separate liste-/detaljspørringer i SQL og domenefeil som oversettes til GraphQL-feil ved resolvergrensen vurderes i senere, avgrensede endringer. @@ -239,8 +245,8 @@ Passordet lagres som Argon2-hash. På Linux: `SEED_PASSWORD='...' npm run db:see - D2-07/09/11/13: frontend er koblet til oppskrifts-API-et, inkludert CRUD og Save/Unsave/Cookbook. - D2-02/15/16: VM-deploy og full nettleserdemonstrasjon må kontrolleres etter integrasjon. Bruk eksisterende Apache/systemd-oppsett og `/project2/api/graphql`. -- D2-14: ratingmutasjoner/reviews er utsatt. Avansert sortering/søk er D3. -- Editable copies og bildeopplasting er ikke inkludert. Databasens sourceRecipeId +- D2-14: ratingmutasjoner er implementert; reviews gjenstår. Avansert sortering/søk er D3. +- Bildeopplasting er implementert; editable copies gjenstår. Databasens sourceRecipeId returneres, men klienten kan ikke endre kildehenvisning via vanlig CRUD-input. AI er brukt til plananalyse, implementasjon og tester. Endringene skal gjennomgås diff --git a/e2e/recipe-api.spec.ts b/e2e/recipe-api.spec.ts index d95fb35..301b6f8 100644 --- a/e2e/recipe-api.spec.ts +++ b/e2e/recipe-api.spec.ts @@ -1,7 +1,9 @@ import { createServer, type Server } from 'node:http'; import { randomUUID } from 'node:crypto'; import { existsSync } from 'node:fs'; -import { readFile } from 'node:fs/promises'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { Pool } from 'pg'; import { expect, test, type BrowserContext, type Page } from '@playwright/test'; import { createApp } from '../apps/api/src/app.js'; @@ -18,8 +20,10 @@ const schema = 'browser_test_' + randomUUID().replaceAll('-', ''); let pool: Pool; let server: Server; let endpoint: string; +let imageDirectory: string; test.beforeAll(async () => { + imageDirectory = await mkdtemp(join(tmpdir(), 'recipe-browser-images-')); pool = new Pool({ connectionString: process.env.DATABASE_URL, connectionTimeoutMillis: 5000, @@ -42,6 +46,7 @@ test.beforeAll(async () => { false, false, { pool, schema }, + imageDirectory, ), ); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); @@ -60,9 +65,19 @@ test.afterAll(async () => { await pool.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); await pool.end(); } + if (imageDirectory?.startsWith(join(tmpdir(), 'recipe-browser-images-'))) + await rm(imageDirectory, { recursive: true, force: true }); }); async function connect(context: BrowserContext) { + await context.route('**/project2/api/uploads**', async (route) => { + const path = new URL(route.request().url()).pathname.replace( + '/project2/api', + '', + ); + const response = await route.fetch({ url: new URL(path, endpoint).href }); + await route.fulfill({ response }); + }); await context.route('**/project2/api/graphql', async (route) => { const response = await route.fetch({ url: endpoint }); await route.fulfill({ response }); @@ -80,7 +95,7 @@ async function register(page: Page, email: string) { ).toBeVisible(); } -test('persists create/edit/save/unsave/private/delete flows through the real API', async ({ +test('persists recipes, uploaded images and ratings through the real API', async ({ page, context, browser, @@ -99,6 +114,22 @@ test('persists create/edit/save/unsave/private/delete flows through the real API await page.getByLabel('Ingredient 1 amount').fill('1'); await page.getByLabel('Ingredient 1 unit').selectOption('l'); await page.getByLabel('Step 1', { exact: true }).fill('Boil water.'); + const image = await page.evaluate(() => { + const canvas = document.createElement('canvas'); + canvas.width = 300; + canvas.height = 200; + const context = canvas.getContext('2d')!; + context.fillStyle = '#f9a825'; + context.fillRect(0, 0, 300, 200); + return canvas.toDataURL('image/png').split(',')[1]!; + }); + await page.getByLabel('Recipe image', { exact: true }).setInputFiles({ + name: 'soup.png', + mimeType: 'image/png', + buffer: Buffer.from(image, 'base64'), + }); + await page.getByRole('button', { name: 'Use image' }).click(); + await expect(page.getByRole('img', { name: 'Recipe preview' })).toBeVisible(); await page.getByRole('button', { name: 'Publish recipe' }).click(); await expect( page.getByRole('heading', { name: 'Browser soup' }), @@ -108,6 +139,14 @@ test('persists create/edit/save/unsave/private/delete flows through the real API await expect( page.getByRole('heading', { name: 'Browser soup' }), ).toBeVisible(); + await expect( + page.getByRole('img', { name: 'Browser soup', exact: true }), + ).toBeVisible(); + expect( + await page + .getByRole('img', { name: 'Browser soup', exact: true }) + .evaluate((image: HTMLImageElement) => image.naturalWidth), + ).toBeGreaterThan(0); await page.getByRole('link', { name: 'Edit Recipe' }).click(); await page.getByLabel(/Recipe title/).fill('Edited browser soup'); await page.getByRole('button', { name: 'Save changes' }).click(); @@ -123,6 +162,23 @@ test('persists create/edit/save/unsave/private/delete flows through the real API const reader = await readerContext.newPage(); await register(reader, 'reader@example.com'); await reader.goto(recipeUrl); + await reader + .getByRole('button', { name: 'Rate this recipe', exact: true }) + .click(); + await reader.getByRole('radio', { name: '5 stars' }).check(); + await reader.getByRole('button', { name: 'Save rating' }).click(); + await expect( + reader.getByRole('button', { name: 'Your rating: 5/5' }), + ).toBeVisible(); + await reader.reload(); + await reader.getByRole('button', { name: 'Your rating: 5/5' }).click(); + await reader.getByRole('radio', { name: '3 stars' }).check(); + await reader.getByRole('button', { name: 'Save rating' }).click(); + await reader.getByRole('button', { name: 'Your rating: 3/5' }).click(); + await reader.getByRole('button', { name: 'Remove rating' }).click(); + await expect( + reader.getByRole('button', { name: 'Rate Recipe' }), + ).toBeVisible(); await reader.getByRole('button', { name: 'Save to Cookbook' }).click(); await expect( reader.getByRole('button', { name: 'Saved', exact: true }), @@ -142,11 +198,15 @@ test('persists create/edit/save/unsave/private/delete flows through the real API ).toBeVisible(); await page.getByRole('link', { name: 'Edit Recipe' }).click(); + await page.getByRole('button', { name: 'Remove image' }).click(); await page.getByLabel('Private', { exact: true }).check(); await page.getByRole('button', { name: 'Save changes' }).click(); await expect( page.getByRole('heading', { name: 'Edited browser soup' }), ).toBeVisible(); + await expect( + page.getByRole('img', { name: 'Edited browser soup', exact: true }), + ).toHaveCount(0); await reader.goto(recipeUrl); await expect( reader.getByRole('heading', { name: 'Recipe not found' }), diff --git a/e2e/smoke.spec.ts b/e2e/smoke.spec.ts index 56e459a..1f29c64 100644 --- a/e2e/smoke.spec.ts +++ b/e2e/smoke.spec.ts @@ -20,6 +20,7 @@ const recipe: RecipeFieldsFragment = { instructions: [], tags: [], rating: { average: 0, count: 0 }, + userRating: null, saveCount: 0, isSaved: false, isCreatedByCurrentUser: false, diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts index d4b1712..aa5eff0 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -22,6 +22,8 @@ import { SaveRecipeDocument, UnsaveRecipeDocument, CookbookDocument, + RateRecipeDocument, + RemoveRecipeRatingDocument, type RecipeInput, } from '../contracts/generated.js'; @@ -221,6 +223,110 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { owner.cookie, ) ).createRecipe; + await t.test( + 'ratings persist per user, update averages and enforce access', + async () => { + await fails( + RateRecipeDocument, + { id: publicRecipe.id, score: 5 }, + 'UNAUTHENTICATED', + ); + await fails( + RateRecipeDocument, + { id: publicRecipe.id, score: 5 }, + 'FORBIDDEN', + owner.cookie, + ); + await fails( + RateRecipeDocument, + { id: privateRecipe.id, score: 5 }, + 'FORBIDDEN', + reader.cookie, + ); + for (const score of [0, 6]) + await fails( + RateRecipeDocument, + { id: publicRecipe.id, score }, + 'BAD_USER_INPUT', + reader.cookie, + ); + const first = ( + await ok( + RateRecipeDocument, + { id: publicRecipe.id, score: 5 }, + reader.cookie, + ) + ).rateRecipe; + assert.deepEqual(first.rating, { average: 5, count: 1 }); + assert.equal(first.userRating, 5); + const updated = ( + await ok( + RateRecipeDocument, + { id: publicRecipe.id, score: 3 }, + reader.cookie, + ) + ).rateRecipe; + assert.deepEqual(updated.rating, { average: 3, count: 1 }); + assert.equal( + (await ok(RecipeDocument, { id: publicRecipe.id }, reader.cookie)) + .recipe?.userRating, + 3, + ); + assert.equal( + (await ok(RecipeDocument, { id: publicRecipe.id }, owner.cookie)) + .recipe?.userRating, + null, + ); + assert.equal( + (await ok(RecipeDocument, { id: publicRecipe.id })).recipe + ?.userRating, + null, + ); + const other = await register('Reviewer', 'reviewer@example.com'); + const combined = ( + await ok( + RateRecipeDocument, + { id: publicRecipe.id, score: 5 }, + other.cookie, + ) + ).rateRecipe; + assert.deepEqual(combined.rating, { average: 4, count: 2 }); + await ok( + RemoveRecipeRatingDocument, + { id: publicRecipe.id }, + owner.cookie, + ); + assert.equal( + (await ok(RecipeDocument, { id: publicRecipe.id })).recipe?.rating + .count, + 2, + ); + await ok( + RemoveRecipeRatingDocument, + { id: publicRecipe.id }, + reader.cookie, + ); + assert.deepEqual( + (await ok(RecipeDocument, { id: publicRecipe.id }, other.cookie)) + .recipe?.rating, + { average: 5, count: 1 }, + ); + await ok( + RemoveRecipeRatingDocument, + { id: publicRecipe.id }, + other.cookie, + ); + await ok( + RemoveRecipeRatingDocument, + { id: publicRecipe.id }, + reader.cookie, + ); + assert.deepEqual( + (await ok(RecipeDocument, { id: publicRecipe.id })).recipe?.rating, + { average: 0, count: 0 }, + ); + }, + ); await t.test( 'creation persists ordered content and uses authenticated author', async () => { From b3fa9bf6de34a71e544e912ff0ac5dd790c24709 Mon Sep 17 00:00:00 2001 From: "hasan.fawzi" Date: Mon, 26 Oct 2026 15:26:27 +0100 Subject: [PATCH 3/6] fix: address integration review and secure image storage --- apps/api/migrations/0004_uploaded_images.sql | 17 + apps/api/migrations/meta/0004_snapshot.json | 801 ++++++++++++++++++ apps/api/migrations/meta/_journal.json | 7 + apps/api/src/app.ts | 8 +- apps/api/src/db/schema.ts | 18 + apps/api/src/features/recipes/imagePaths.ts | 9 + .../src/features/recipes/imageRepository.ts | 31 + .../src/features/recipes/imageStorage.test.ts | 114 ++- apps/api/src/features/recipes/imageStorage.ts | 38 +- apps/api/src/features/recipes/imageStore.ts | 171 ++++ .../src/features/recipes/recipeRepository.ts | 10 + .../src/features/recipes/recipeValidation.ts | 2 +- apps/api/src/server.ts | 23 + apps/web/src/data/recipes.ts | 773 ----------------- .../cookbook/mockCookbookQuery.test.ts | 184 ---- .../features/cookbook/mockCookbookQuery.ts | 110 --- .../features/explore/mockExploreQuery.test.ts | 271 ------ .../src/features/explore/mockExploreQuery.ts | 128 --- .../recipe-detail/RecipeDetailPage.tsx | 43 +- .../recipes/RecipeCreatePage.test.tsx | 55 +- .../src/features/recipes/RecipeCreatePage.tsx | 28 +- .../src/features/recipes/RecipeImageField.tsx | 5 +- .../features/recipes/RecipeQueryStatus.tsx | 10 +- .../src/features/recipes/recipeImages.test.ts | 27 + apps/web/src/features/recipes/recipeImages.ts | 53 +- .../features/recipes/useRecipeQuery.test.tsx | 80 ++ .../src/features/recipes/useRecipeQuery.ts | 50 +- docs/frontend-integration.md | 15 +- docs/recipe-api.md | 6 +- docs/review-test-guide.md | 78 ++ e2e/recipe-api.spec.ts | 9 + package.json | 3 +- scripts/cleanup-images.ts | 17 + scripts/test-database.ts | 12 + scripts/test-recipe-api.ts | 149 +++- scripts/tsconfig.json | 2 +- 36 files changed, 1734 insertions(+), 1623 deletions(-) create mode 100644 apps/api/migrations/0004_uploaded_images.sql create mode 100644 apps/api/migrations/meta/0004_snapshot.json create mode 100644 apps/api/src/features/recipes/imagePaths.ts create mode 100644 apps/api/src/features/recipes/imageRepository.ts create mode 100644 apps/api/src/features/recipes/imageStore.ts delete mode 100644 apps/web/src/data/recipes.ts delete mode 100644 apps/web/src/features/cookbook/mockCookbookQuery.test.ts delete mode 100644 apps/web/src/features/cookbook/mockCookbookQuery.ts delete mode 100644 apps/web/src/features/explore/mockExploreQuery.test.ts delete mode 100644 apps/web/src/features/explore/mockExploreQuery.ts create mode 100644 apps/web/src/features/recipes/recipeImages.test.ts create mode 100644 apps/web/src/features/recipes/useRecipeQuery.test.tsx create mode 100644 docs/review-test-guide.md create mode 100644 scripts/cleanup-images.ts diff --git a/apps/api/migrations/0004_uploaded_images.sql b/apps/api/migrations/0004_uploaded_images.sql new file mode 100644 index 0000000..1872800 --- /dev/null +++ b/apps/api/migrations/0004_uploaded_images.sql @@ -0,0 +1,17 @@ +CREATE TABLE "project2"."uploaded_images" ( + "filename" text PRIMARY KEY NOT NULL, + "owner_id" uuid, + "byte_size" integer NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "uploaded_images_size_valid" CHECK ("project2"."uploaded_images"."byte_size" >= 0) +); +--> statement-breakpoint +ALTER TABLE "project2"."uploaded_images" ADD CONSTRAINT "uploaded_images_owner_id_users_id_fk" FOREIGN KEY ("owner_id") REFERENCES "project2"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "uploaded_images_owner_idx" ON "project2"."uploaded_images" USING btree ("owner_id"); +--> statement-breakpoint +INSERT INTO "project2"."uploaded_images" (filename, owner_id, byte_size, created_at) +SELECT DISTINCT ON (image_url) substring(image_url from 10), author_id, 0, created_at +FROM "project2"."recipes" +WHERE image_url ~ '^/uploads/[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\.(jpg|png|webp)$' +ORDER BY image_url, created_at +ON CONFLICT DO NOTHING; diff --git a/apps/api/migrations/meta/0004_snapshot.json b/apps/api/migrations/meta/0004_snapshot.json new file mode 100644 index 0000000..0608408 --- /dev/null +++ b/apps/api/migrations/meta/0004_snapshot.json @@ -0,0 +1,801 @@ +{ + "id": "ecd5b606-3009-44eb-a2a2-bfc879930465", + "prevId": "c0ecbb19-5a20-4d7a-808d-836ae2992c9e", + "version": "7", + "dialect": "postgresql", + "tables": { + "project2.ratings": { + "name": "ratings", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "score": { + "name": "score", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "ratings_recipe_idx": { + "name": "ratings_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "ratings_user_id_users_id_fk": { + "name": "ratings_user_id_users_id_fk", + "tableFrom": "ratings", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "ratings_recipe_id_recipes_id_fk": { + "name": "ratings_recipe_id_recipes_id_fk", + "tableFrom": "ratings", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "ratings_user_id_recipe_id_pk": { + "name": "ratings_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "ratings_score_valid": { + "name": "ratings_score_valid", + "value": "\"project2\".\"ratings\".\"score\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_ingredients": { + "name": "recipe_ingredients", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "numeric(12, 4)", + "primaryKey": false, + "notNull": true + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_ingredients_recipe_position_unique": { + "name": "recipe_ingredients_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_ingredients_recipe_id_recipes_id_fk": { + "name": "recipe_ingredients_recipe_id_recipes_id_fk", + "tableFrom": "recipe_ingredients", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_ingredients_name_not_blank": { + "name": "recipe_ingredients_name_not_blank", + "value": "length(trim(\"project2\".\"recipe_ingredients\".\"name\")) > 0" + }, + "recipe_ingredients_amount_positive": { + "name": "recipe_ingredients_amount_positive", + "value": "\"project2\".\"recipe_ingredients\".\"amount\" > 0 AND \"project2\".\"recipe_ingredients\".\"amount\" <> 'NaN'::numeric" + }, + "recipe_ingredients_position_positive": { + "name": "recipe_ingredients_position_positive", + "value": "\"project2\".\"recipe_ingredients\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_instructions": { + "name": "recipe_instructions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_instructions_recipe_position_unique": { + "name": "recipe_instructions_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_instructions_recipe_id_recipes_id_fk": { + "name": "recipe_instructions_recipe_id_recipes_id_fk", + "tableFrom": "recipe_instructions", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_instructions_text_not_blank": { + "name": "recipe_instructions_text_not_blank", + "value": "length(trim(\"project2\".\"recipe_instructions\".\"text\")) > 0" + }, + "recipe_instructions_position_positive": { + "name": "recipe_instructions_position_positive", + "value": "\"project2\".\"recipe_instructions\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_tags": { + "name": "recipe_tags", + "schema": "project2", + "columns": { + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "recipe_tags_recipe_id_recipes_id_fk": { + "name": "recipe_tags_recipe_id_recipes_id_fk", + "tableFrom": "recipe_tags", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "recipe_tags_recipe_id_tag_pk": { + "name": "recipe_tags_recipe_id_tag_pk", + "columns": ["recipe_id", "tag"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_tags_normalized": { + "name": "recipe_tags_normalized", + "value": "length(\"project2\".\"recipe_tags\".\"tag\") > 0 AND \"project2\".\"recipe_tags\".\"tag\" = lower(trim(\"project2\".\"recipe_tags\".\"tag\"))" + } + }, + "isRLSEnabled": false + }, + "project2.recipes": { + "name": "recipes", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_recipe_id": { + "name": "source_recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "image_url": { + "name": "image_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cuisine": { + "name": "cuisine", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "difficulty": { + "name": "difficulty", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'private'" + }, + "prep_minutes": { + "name": "prep_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cook_minutes": { + "name": "cook_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "servings": { + "name": "servings", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "recipes_author_idx": { + "name": "recipes_author_idx", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_source_idx": { + "name": "recipes_source_idx", + "columns": [ + { + "expression": "source_recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_public_created_idx": { + "name": "recipes_public_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipes_author_id_users_id_fk": { + "name": "recipes_author_id_users_id_fk", + "tableFrom": "recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["author_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "recipes_source_recipe_id_recipes_id_fk": { + "name": "recipes_source_recipe_id_recipes_id_fk", + "tableFrom": "recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["source_recipe_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipes_title_not_blank": { + "name": "recipes_title_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"title\")) > 0" + }, + "recipes_category_valid": { + "name": "recipes_category_valid", + "value": "\"project2\".\"recipes\".\"category\" IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')" + }, + "recipes_cuisine_not_blank": { + "name": "recipes_cuisine_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"cuisine\")) > 0" + }, + "recipes_difficulty_valid": { + "name": "recipes_difficulty_valid", + "value": "\"project2\".\"recipes\".\"difficulty\" IN ('easy', 'medium', 'hard')" + }, + "recipes_visibility_valid": { + "name": "recipes_visibility_valid", + "value": "\"project2\".\"recipes\".\"visibility\" IN ('public', 'private')" + }, + "recipes_prep_minutes_nonnegative": { + "name": "recipes_prep_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"prep_minutes\" >= 0" + }, + "recipes_cook_minutes_nonnegative": { + "name": "recipes_cook_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"cook_minutes\" >= 0" + }, + "recipes_servings_positive": { + "name": "recipes_servings_positive", + "value": "\"project2\".\"recipes\".\"servings\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.saved_recipes": { + "name": "saved_recipes", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "saved_recipes_recipe_idx": { + "name": "saved_recipes_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "saved_recipes_user_id_users_id_fk": { + "name": "saved_recipes_user_id_users_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "saved_recipes_recipe_id_recipes_id_fk": { + "name": "saved_recipes_recipe_id_recipes_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "saved_recipes_user_id_recipe_id_pk": { + "name": "saved_recipes_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.sessions": { + "name": "sessions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.uploaded_images": { + "name": "uploaded_images", + "schema": "project2", + "columns": { + "filename": { + "name": "filename", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "byte_size": { + "name": "byte_size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "uploaded_images_owner_idx": { + "name": "uploaded_images_owner_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "uploaded_images_owner_id_users_id_fk": { + "name": "uploaded_images_owner_id_users_id_fk", + "tableFrom": "uploaded_images", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["owner_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "uploaded_images_size_valid": { + "name": "uploaded_images_size_valid", + "value": "\"project2\".\"uploaded_images\".\"byte_size\" >= 0" + } + }, + "isRLSEnabled": false + }, + "project2.users": { + "name": "users", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/apps/api/migrations/meta/_journal.json b/apps/api/migrations/meta/_journal.json index 4d08ec8..13c88f1 100644 --- a/apps/api/migrations/meta/_journal.json +++ b/apps/api/migrations/meta/_journal.json @@ -29,6 +29,13 @@ "when": 1791796199161, "tag": "0003_recipe_review", "breakpoints": true + }, + { + "idx": 4, + "version": "7", + "when": 1793008961317, + "tag": "0004_uploaded_images", + "breakpoints": true } ] } diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 7417bad..26232d3 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -1,6 +1,7 @@ import type { Pool } from 'pg'; import { fileURLToPath } from 'node:url'; import { handleImageRequest } from './features/recipes/imageStorage.js'; +import { createImageStore } from './features/recipes/imageStore.js'; import { db } from './db/client.js'; import { createRecipeRepository } from './features/recipes/recipeRepository.js'; import { createRecipeResolvers } from './features/recipes/recipeResolvers.js'; @@ -29,6 +30,11 @@ export function createApp( uploadDirectory = process.env.UPLOAD_DIR ?? fileURLToPath(new URL('../../../uploads/', import.meta.url)), ) { + const images = createImageStore( + database.pool ?? db, + database.schema ?? 'project2', + uploadDirectory, + ); const authResolvers = createAuthResolvers(service); const recipes = createRecipeResolvers( createRecipeRepository(database.pool ?? db, database.schema ?? 'project2'), @@ -45,7 +51,7 @@ export function createApp( const imageResponse = await handleImageRequest( request, service, - uploadDirectory, + images, ); if (imageResponse) { endResponse(imageResponse); diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts index cc6c5f3..2ac1a59 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -210,3 +210,21 @@ export const ratings = project2.table( check('ratings_score_valid', sql`${table.score} BETWEEN 1 AND 5`), ], ); + +export const uploadedImages = project2.table( + 'uploaded_images', + { + filename: text().primaryKey(), + ownerId: uuid('owner_id').references(() => users.id, { + onDelete: 'set null', + }), + byteSize: integer('byte_size').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + index('uploaded_images_owner_idx').on(table.ownerId), + check('uploaded_images_size_valid', sql`${table.byteSize} >= 0`), + ], +); diff --git a/apps/api/src/features/recipes/imagePaths.ts b/apps/api/src/features/recipes/imagePaths.ts new file mode 100644 index 0000000..336ec24 --- /dev/null +++ b/apps/api/src/features/recipes/imagePaths.ts @@ -0,0 +1,9 @@ +const filenameSource = + '[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}\\.(jpg|png|webp)'; +export const imageFilenamePattern = new RegExp(`^${filenameSource}$`); +export const uploadedImagePattern = new RegExp(`^/uploads/${filenameSource}$`); +export function uploadedImageFilename(url: string | null | undefined) { + return url && uploadedImagePattern.test(url) + ? url.slice('/uploads/'.length) + : null; +} diff --git a/apps/api/src/features/recipes/imageRepository.ts b/apps/api/src/features/recipes/imageRepository.ts new file mode 100644 index 0000000..8c0c1a7 --- /dev/null +++ b/apps/api/src/features/recipes/imageRepository.ts @@ -0,0 +1,31 @@ +import { GraphQLError } from 'graphql'; +import type { PoolClient } from 'pg'; +import { uploadedImageFilename } from './imagePaths.js'; + +export async function lockImages(client: PoolClient, schema: string) { + await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [ + `${schema}:uploaded_images`, + ]); +} + +export async function validateImageReference( + client: PoolClient, + schema: string, + url: string | null, + userId: string, + recipeId?: string, +) { + // Serialize attachment with upload/cleanup, including removal of an old reference. + await lockImages(client, schema); + const filename = uploadedImageFilename(url); + if (!filename) return; + const result = await client.query( + `SELECT 1 FROM "${schema}".uploaded_images i WHERE i.filename=$1 AND + (i.owner_id=$2::uuid OR EXISTS(SELECT 1 FROM "${schema}".recipes r WHERE r.id=$3::uuid AND r.author_id=$2::uuid AND r.image_url=$4))`, + [filename, userId, recipeId ?? null, url], + ); + if (!result.rowCount) + throw new GraphQLError('Choose an image uploaded by you.', { + extensions: { code: 'BAD_USER_INPUT' }, + }); +} diff --git a/apps/api/src/features/recipes/imageStorage.test.ts b/apps/api/src/features/recipes/imageStorage.test.ts index 388548e..e91a3e0 100644 --- a/apps/api/src/features/recipes/imageStorage.test.ts +++ b/apps/api/src/features/recipes/imageStorage.test.ts @@ -1,9 +1,7 @@ -import { mkdtemp, readdir, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; -import { createApp } from '../../app.js'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { handleImageRequest } from './imageStorage.js'; import type { AuthService } from '../auth/authService.js'; +import type { ImageStore } from './imageStore.js'; const token = '11111111-1111-4111-8111-111111111111'; const user = { id: token, name: 'Test Cook', email: 'cook@example.com' }; @@ -13,71 +11,63 @@ const service: AuthService = { register: async () => ({ user, sessionToken: token }), signOut: async () => true, }; -// A complete 1x1 PNG, also used to verify bytes survive storage unchanged. const png = Buffer.from( 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aOioAAAAASUVORK5CYII=', 'base64', ); -let directory: string; -beforeAll(async () => { - directory = await mkdtemp(join(tmpdir(), 'recipe-images-')); -}); -afterAll(async () => { - if (directory.startsWith(join(tmpdir(), 'recipe-images-'))) - await rm(directory, { recursive: true, force: true }); -}); -function upload(body: Buffer, headers: Record = {}) { - const app = createApp(service, false, false, {}, directory); - return app.fetch('http://localhost/uploads', { - method: 'POST', - body: new Uint8Array(body), - headers: { - 'Content-Type': 'image/png', - 'X-Requested-With': 'recipe-platform', - Cookie: `t31_project2_session=${token}`, - ...headers, - }, - }); +const store: ImageStore = { + upload: vi.fn(async () => `/uploads/${token}.png`), + read: vi.fn(async () => png), + cleanup: vi.fn(async () => 0), +}; +beforeEach(() => vi.clearAllMocks()); +function upload(body = png, headers: Record = {}) { + return handleImageRequest( + new Request('http://localhost/uploads', { + method: 'POST', + body: new Uint8Array(body), + headers: { + 'Content-Type': 'image/png', + 'X-Requested-With': 'recipe-platform', + Cookie: `t31_project2_session=${token}`, + ...headers, + }, + }), + service, + store, + ); } - -describe('local image storage', () => { - it('persists an image and serves it after recreating the app', async () => { - const response = await upload(png); - expect(response.status).toBe(201); - const { imageUrl } = (await response.json()) as { imageUrl: string }; - expect(imageUrl).toMatch(/^\/uploads\/[0-9a-f-]+\.png$/); - const restarted = createApp(service, false, false, {}, directory); - const image = await restarted.fetch(`http://localhost${imageUrl}`); - expect(image.status).toBe(200); - expect(image.headers.get('content-type')).toBe('image/png'); - expect(image.headers.get('x-content-type-options')).toBe('nosniff'); - expect(Buffer.from(await image.arrayBuffer())).toEqual(png); - }); - it('requires login and the same custom request header as GraphQL', async () => { - expect((await upload(png, { Cookie: '' })).status).toBe(401); - expect((await upload(png, { 'X-Requested-With': '' })).status).toBe(403); +describe('image upload boundary', () => { + it('validates bytes and records the authenticated owner', async () => { + expect((await upload())?.status).toBe(201); + expect(store.upload).toHaveBeenCalledWith(user.id, png, 'png'); }); - it('rejects unsupported, spoofed and oversized bodies without writing files', async () => { - const before = await readdir(directory); - expect( - (await upload(png, { 'Content-Type': 'image/svg+xml' })).status, - ).toBe(415); - expect((await upload(Buffer.from(''))).status).toBe( - 415, - ); - expect((await upload(png, { 'Content-Type': 'image/jpeg' })).status).toBe( + it('rejects anonymous, cross-origin-style and invalid uploads before storage', async () => { + expect((await upload(png, { Cookie: '' }))?.status).toBe(401); + expect((await upload(png, { 'X-Requested-With': '' }))?.status).toBe(403); + expect((await upload(Buffer.from('')))?.status).toBe( 415, ); - expect((await upload(Buffer.alloc(5 * 1024 * 1024 + 1))).status).toBe(413); - expect(await readdir(directory)).toEqual(before); + expect((await upload(Buffer.alloc(5 * 1024 * 1024 + 1)))?.status).toBe(413); + expect(store.upload).not.toHaveBeenCalled(); }); - it('does not serve arbitrary filenames or missing images', async () => { - const app = createApp(service, false, false, {}, directory); - for (const path of [ - '/uploads/.env', - '/uploads/%2e%2e%2f.env', - '/uploads/11111111-1111-4111-8111-111111111111.jpg', - ]) - expect((await app.fetch('http://localhost' + path)).status).toBe(404); + it('rejects unsafe paths before looking up files and never caches images', async () => { + expect( + ( + await handleImageRequest( + new Request('http://localhost/uploads/%2e%2e%2f.env'), + service, + store, + ) + )?.status, + ).toBe(404); + expect(store.read).not.toHaveBeenCalled(); + const response = await handleImageRequest( + new Request(`http://localhost/uploads/${token}.png`), + service, + store, + ); + expect(response?.headers.get('cache-control')).toBe('no-store'); + expect(store.read).toHaveBeenCalledWith(`${token}.png`, null); }); }); diff --git a/apps/api/src/features/recipes/imageStorage.ts b/apps/api/src/features/recipes/imageStorage.ts index 1ac9e09..e26be81 100644 --- a/apps/api/src/features/recipes/imageStorage.ts +++ b/apps/api/src/features/recipes/imageStorage.ts @@ -1,14 +1,9 @@ -import { randomUUID } from 'node:crypto'; -import { mkdir, readFile, writeFile } from 'node:fs/promises'; -import { join } from 'node:path'; import type { AuthService } from '../auth/authService.js'; import { readSessionCookie } from '../auth/sessionCookie.js'; +import { imageFilenamePattern } from './imagePaths.js'; +import { ImageError, type ImageStore } from './imageStore.js'; const MAX_BYTES = 5 * 1024 * 1024; -const filePattern = - /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}\.(jpg|png|webp)$/; -export const uploadedImagePattern = - /^\/uploads\/[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}\.(jpg|png|webp)$/; const contentTypes: Record = { jpg: 'image/jpeg', png: 'image/png', @@ -30,27 +25,34 @@ function imageExtension(bytes: Buffer) { } function failure(status: number, message: string) { - return Response.json({ message }, { status }); + return Response.json( + { message }, + { status, headers: { 'Cache-Control': 'no-store' } }, + ); } // A single upload endpoint and a restricted file route; client filenames are never used. export async function handleImageRequest( request: Request, service: AuthService, - directory: string, + store: ImageStore, ): Promise { const path = new URL(request.url).pathname; if (path !== '/uploads' && !path.startsWith('/uploads/')) return null; try { if (request.method === 'GET' && path.startsWith('/uploads/')) { const filename = path.slice('/uploads/'.length); - if (!filePattern.test(filename)) return failure(404, 'Image not found.'); + if (!imageFilenamePattern.test(filename)) + return failure(404, 'Image not found.'); try { - const image = await readFile(join(directory, filename)); + const token = readSessionCookie(request); + const user = token ? await service.currentUser(token) : null; + const image = await store.read(filename, user?.id ?? null); return new Response(new Uint8Array(image), { headers: { 'Content-Type': contentTypes[filename.split('.').pop()!]!, 'X-Content-Type-Options': 'nosniff', + 'Cache-Control': 'no-store', }, }); } catch (error) { @@ -64,8 +66,8 @@ export async function handleImageRequest( if (request.headers.get('x-requested-with') !== 'recipe-platform') return failure(403, 'Request blocked.'); const token = readSessionCookie(request); - if (!token || !(await service.currentUser(token))) - return failure(401, 'Please sign in to upload an image.'); + const user = token ? await service.currentUser(token) : null; + if (!user) return failure(401, 'Please sign in to upload an image.'); const type = request.headers.get('content-type')?.split(';')[0]; if (!type || !Object.values(contentTypes).includes(type)) return failure(415, 'Choose a JPG, PNG, or WebP image.'); @@ -93,11 +95,11 @@ export async function handleImageRequest( const extension = imageExtension(image); if (!extension || contentTypes[extension] !== type) return failure(415, 'The file must contain a JPG, PNG, or WebP image.'); - await mkdir(directory, { recursive: true }); - const filename = `${randomUUID()}.${extension}`; - await writeFile(join(directory, filename), image, { flag: 'wx' }); - return Response.json({ imageUrl: `/uploads/${filename}` }, { status: 201 }); - } catch { + const imageUrl = await store.upload(user.id, image, extension); + return Response.json({ imageUrl }, { status: 201 }); + } catch (error) { + if (error instanceof ImageError) + return failure(error.status, error.message); return failure(500, 'Unable to store the image. Please try again.'); } } diff --git a/apps/api/src/features/recipes/imageStore.ts b/apps/api/src/features/recipes/imageStore.ts new file mode 100644 index 0000000..a76b17e --- /dev/null +++ b/apps/api/src/features/recipes/imageStore.ts @@ -0,0 +1,171 @@ +import { + readdir, + stat, + unlink, + mkdir, + writeFile, + readFile, +} from 'node:fs/promises'; +import { join } from 'node:path'; +import { randomUUID } from 'node:crypto'; +import type { Pool, PoolClient } from 'pg'; +import { imageFilenamePattern } from './imagePaths.js'; +import { lockImages } from './imageRepository.js'; + +export class ImageError extends Error { + constructor( + public status: number, + message: string, + ) { + super(message); + } +} + +const DEFAULT_LIMITS = { + userBytes: 100 * 1024 * 1024, + totalBytes: 1024 * 1024 * 1024, + totalFiles: 1000, + perHour: 20, +}; +export function createImageStore( + pool: Pool, + schema: string, + directory: string, + limits = DEFAULT_LIMITS, +) { + if (!/^[a-z_][a-z0-9_]*$/.test(schema)) + throw new Error('Invalid database schema.'); + const images = `"${schema}".uploaded_images`; + const recipes = `"${schema}".recipes`; + const reference = `EXISTS(SELECT 1 FROM ${recipes} r WHERE r.image_url='/uploads/' || i.filename)`; + + async function locked(work: (client: PoolClient) => Promise) { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + await lockImages(client, schema); + const result = await work(client); + await client.query('COMMIT'); + return result; + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } finally { + client.release(); + } + } + async function files() { + await mkdir(directory, { recursive: true }); + const names = (await readdir(directory)).filter((name) => + imageFilenamePattern.test(name), + ); + const result: Array<{ name: string; size: number; modified: number }> = []; + for (const name of names) { + try { + const info = await stat(join(directory, name)); + if (info.isFile()) + result.push({ name, size: info.size, modified: info.mtimeMs }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + } + return result; + } + async function removeFile(filename: string) { + try { + await unlink(join(directory, filename)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + } + return { + async upload(userId: string, bytes: Buffer, extension: string) { + return locked(async (client) => { + const usage = await client.query<{ bytes: string; recent: number }>( + `SELECT coalesce(sum(byte_size),0) AS bytes, count(*) FILTER (WHERE created_at > now()-interval '1 hour')::int AS recent FROM ${images} WHERE owner_id=$1`, + [userId], + ); + if (usage.rows[0]!.recent >= limits.perHour) + throw new ImageError(429, 'Too many uploads. Try again in an hour.'); + if (Number(usage.rows[0]!.bytes) + bytes.length > limits.userBytes) + throw new ImageError( + 413, + 'Your image storage limit has been reached.', + ); + const stored = await files(); + if ( + stored.length >= limits.totalFiles || + stored.reduce((sum, file) => sum + file.size, 0) + bytes.length > + limits.totalBytes + ) + throw new ImageError( + 507, + 'Image storage is full. Please try again later.', + ); + const filename = `${randomUUID()}.${extension}`; + if (!imageFilenamePattern.test(filename)) + throw new ImageError(415, 'Unsupported image type.'); + let written = false; + try { + await writeFile(join(directory, filename), bytes, { flag: 'wx' }); + written = true; + await client.query( + `INSERT INTO ${images} (filename,owner_id,byte_size) VALUES ($1,$2,$3)`, + [filename, userId, bytes.length], + ); + } catch (error) { + if (written) await removeFile(filename); + throw error; + } + return `/uploads/${filename}`; + }); + }, + async read(filename: string, userId: string | null) { + const allowed = await pool.query( + `SELECT 1 FROM ${images} i WHERE i.filename=$1 AND ( + EXISTS(SELECT 1 FROM ${recipes} r WHERE r.image_url='/uploads/' || i.filename AND (r.visibility='public' OR r.author_id=$2::uuid)) + OR (i.owner_id=$2::uuid AND NOT ${reference}))`, + [filename, userId], + ); + if (!allowed.rowCount) throw new ImageError(404, 'Image not found.'); + try { + return await readFile(join(directory, filename)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') + throw new ImageError(404, 'Image not found.'); + throw error; + } + }, + async cleanup() { + return locked(async (client) => { + const stored = await files(); + let removed = 0; + for (const file of stored) { + // Reconcile metadata for legacy referenced images before applying quotas. + await client.query( + `UPDATE ${images} SET byte_size=$2 WHERE filename=$1`, + [file.name, file.size], + ); + if (file.modified > Date.now() - 24 * 60 * 60 * 1000) continue; + const protectedFile = await client.query( + `SELECT 1 FROM ${recipes} WHERE image_url=$1 UNION ALL SELECT 1 FROM ${images} WHERE filename=$2 AND created_at > now()-interval '24 hours'`, + [`/uploads/${file.name}`, file.name], + ); + if (protectedFile.rowCount) continue; + await removeFile(file.name); + await client.query(`DELETE FROM ${images} WHERE filename=$1`, [ + file.name, + ]); + removed += 1; + } + // Missing files must not leave permanent quota usage behind. + await client.query( + `DELETE FROM ${images} i WHERE NOT ${reference} AND created_at < now()-interval '24 hours' AND NOT (filename=ANY($1::text[]))`, + [stored.map((file) => file.name)], + ); + return removed; + }); + }, + }; +} +export type ImageStore = ReturnType; diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index 4beff56..98e7505 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -3,6 +3,7 @@ import type { Pool, PoolClient } from 'pg'; import { db } from '../../db/client.js'; import type { CookbookScope, Recipe } from '../../generated.js'; import type { RecipeInput, ListInput } from './recipeValidation.js'; +import { validateImageReference, lockImages } from './imageRepository.js'; export function createRecipeRepository(pool: Pool = db, schema = 'project2') { if (!/^[a-z_][a-z0-9_]*$/.test(schema)) @@ -167,6 +168,7 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { }, async create(input: RecipeInput, userId: string) { return transaction(async (client) => { + await validateImageReference(client, schema, input.imageUrl, userId); const result = await client.query<{ id: string }>( `INSERT INTO ${t('recipes')} (title,description,image_url,category,cuisine,difficulty,visibility,prep_minutes,cook_minutes,servings,author_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING id`, [...values(input), userId], @@ -179,6 +181,13 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { async update(id: string, input: RecipeInput, userId: string) { return transaction(async (client) => { await owned(client, id, userId); + await validateImageReference( + client, + schema, + input.imageUrl, + userId, + id, + ); await client.query( `UPDATE ${t('recipes')} SET title=$1,description=$2,image_url=$3,category=$4,cuisine=$5,difficulty=$6,visibility=$7,prep_minutes=$8,cook_minutes=$9,servings=$10 WHERE id=$11`, [...values(input), id], @@ -196,6 +205,7 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { async delete(id: string, userId: string) { return transaction(async (client) => { await owned(client, id, userId); + await lockImages(client, schema); await client.query(`DELETE FROM ${t('recipes')} WHERE id=$1`, [id]); return true; }); diff --git a/apps/api/src/features/recipes/recipeValidation.ts b/apps/api/src/features/recipes/recipeValidation.ts index 89e022a..deb3ec5 100644 --- a/apps/api/src/features/recipes/recipeValidation.ts +++ b/apps/api/src/features/recipes/recipeValidation.ts @@ -1,6 +1,6 @@ import { GraphQLError } from 'graphql'; import { z } from 'zod'; -import { uploadedImagePattern } from './imageStorage.js'; +import { uploadedImagePattern } from './imagePaths.js'; export const categorySchema = z.enum([ 'breakfast', diff --git a/apps/api/src/server.ts b/apps/api/src/server.ts index 550b779..6877acd 100644 --- a/apps/api/src/server.ts +++ b/apps/api/src/server.ts @@ -1,5 +1,28 @@ import { createServer } from 'node:http'; import { app } from './app.js'; +import { fileURLToPath } from 'node:url'; +import { db } from './db/client.js'; +import { createImageStore } from './features/recipes/imageStore.js'; + +const images = createImageStore( + db, + 'project2', + process.env.UPLOAD_DIR ?? + fileURLToPath(new URL('../../../uploads/', import.meta.url)), +); +const cleanup = () => + images + .cleanup() + .catch(() => + console.error('Image cleanup failed; it will retry in one hour.'), + ); +void cleanup(); +setInterval( + () => { + void cleanup(); + }, + 60 * 60 * 1000, +).unref(); createServer(app).listen( Number(process.env.API_PORT ?? 3001), diff --git a/apps/web/src/data/recipes.ts b/apps/web/src/data/recipes.ts deleted file mode 100644 index a103eaa..0000000 --- a/apps/web/src/data/recipes.ts +++ /dev/null @@ -1,773 +0,0 @@ -import type { Recipe, UserSummary } from '../types/recipe'; - -export const currentUser: UserSummary = { - id: 'user-hasan', - name: 'Hasan', -}; - -const emma: UserSummary = { - id: 'user-emma', - name: 'Emma Larsen', -}; - -const yusuf: UserSummary = { - id: 'user-yusuf', - name: 'Yusuf Demir', -}; - -const nora: UserSummary = { - id: 'user-nora', - name: 'Nora Berg', -}; - -export const recipes: Recipe[] = [ - { - id: 'shakshuka', - title: 'Spicy shakshuka with herbs', - description: - 'Eggs poached in a rich tomato sauce with peppers, cumin and fresh herbs.', - category: 'Breakfast', - cuisine: 'Middle Eastern', - difficulty: 'easy', - prepMinutes: 10, - cookMinutes: 25, - servings: 4, - tags: ['vegetarian', 'one-pan', 'breakfast'], - imageUrl: - 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR3i3sftsOhCx75YM5uWz6DpUYIzKqkfX5xgvJLnOnyvg&s=10', - author: yusuf, - ingredients: [ - { - id: 'shakshuka-tomatoes', - name: 'Chopped tomatoes', - amount: 800, - unit: 'g', - }, - { - id: 'shakshuka-eggs', - name: 'Eggs', - amount: 4, - unit: 'pcs', - }, - { - id: 'shakshuka-pepper', - name: 'Red pepper', - amount: 1, - unit: 'pc', - }, - ], - instructions: [ - { step: 1, text: 'Cook the pepper until soft.' }, - { step: 2, text: 'Add tomatoes and spices, then simmer.' }, - { step: 3, text: 'Add the eggs and cook until set.' }, - ], - rating: { average: 4.8, count: 126 }, - saveCount: 200, - visibility: 'public', - isSaved: true, - isCreatedByCurrentUser: false, - createdAt: '2026-08-01T10:00:00Z', - updatedAt: '2026-09-10T14:30:00Z', - }, - { - id: 'salmon-pasta', - title: 'Creamy salmon pasta', - description: - 'A quick pasta dinner with salmon, lemon, spinach and a creamy sauce.', - category: 'Dinner', - cuisine: 'European', - difficulty: 'easy', - prepMinutes: 10, - cookMinutes: 20, - servings: 4, - tags: ['pasta', 'seafood', 'quick'], - imageUrl: - 'https://www.crunchtimekitchen.com/wp-content/uploads/2024/04/Lemon-Linguine-feature-Feature-1520x1013.jpg', - author: emma, - ingredients: [ - { - id: 'salmon-pasta-pasta', - name: 'Pasta', - amount: 400, - unit: 'g', - }, - { - id: 'salmon-pasta-salmon', - name: 'Salmon fillet', - amount: 350, - unit: 'g', - }, - { - id: 'salmon-pasta-spinach', - name: 'Spinach', - amount: 100, - unit: 'g', - }, - ], - instructions: [ - { step: 1, text: 'Cook the pasta according to the package.' }, - { step: 2, text: 'Fry the salmon and add cream and spinach.' }, - { step: 3, text: 'Combine with pasta and season with lemon.' }, - ], - rating: { average: 4.6, count: 89 }, - saveCount: 150, - visibility: 'public', - isSaved: false, - isCreatedByCurrentUser: false, - createdAt: '2026-08-04T09:00:00Z', - updatedAt: '2026-08-04T09:00:00Z', - }, - { - id: 'lentil-soup', - title: 'Red lentil soup', - description: - 'A warming and affordable soup with lentils, carrots and mild spices.', - category: 'Soup', - cuisine: 'Turkish', - difficulty: 'easy', - prepMinutes: 10, - cookMinutes: 35, - servings: 6, - tags: ['vegan', 'budget', 'soup'], - imageUrl: - 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcREc6I7Eh7Id8ShR_DFGqrN_fWRgWw7JJV-5xtCAvmwH4nNLOcz15U6Qvg&s=10', - author: currentUser, - ingredients: [ - { - id: 'lentil-soup-lentils', - name: 'Red lentils', - amount: 300, - unit: 'g', - }, - { - id: 'lentil-soup-carrots', - name: 'Carrots', - amount: 2, - unit: 'pcs', - }, - { - id: 'lentil-soup-stock', - name: 'Vegetable stock', - amount: 1.2, - unit: 'l', - }, - ], - instructions: [ - { step: 1, text: 'Rinse the lentils and chop the vegetables.' }, - { step: 2, text: 'Simmer all ingredients until soft.' }, - { step: 3, text: 'Blend until smooth and adjust seasoning.' }, - ], - rating: { average: 4.5, count: 37 }, - saveCount: 20, - visibility: 'public', - isSaved: false, - isCreatedByCurrentUser: true, - createdAt: '2026-08-08T11:00:00Z', - updatedAt: '2026-09-14T18:00:00Z', - }, - { - id: 'chicken-biryani', - title: 'Chicken biryani', - description: - 'Aromatic rice with marinated chicken, warm spices and caramelized onion.', - category: 'Dinner', - cuisine: 'South Asian', - difficulty: 'hard', - prepMinutes: 30, - cookMinutes: 60, - servings: 6, - tags: ['rice', 'chicken', 'spicy', 'weekend'], - imageUrl: - 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTXUu2IadiC7B2-y2_FpLd96CB8y9jzmw_Dm7gnkaA4KZJJVL2AM5mGQVLc&s=10', - author: yusuf, - ingredients: [ - { - id: 'biryani-rice', - name: 'Basmati rice', - amount: 500, - unit: 'g', - }, - { - id: 'biryani-chicken', - name: 'Chicken thighs', - amount: 800, - unit: 'g', - }, - { - id: 'biryani-yoghurt', - name: 'Natural yoghurt', - amount: 200, - unit: 'g', - }, - ], - instructions: [ - { step: 1, text: 'Marinate the chicken with yoghurt and spices.' }, - { step: 2, text: 'Partially cook the rice.' }, - { step: 3, text: 'Layer chicken and rice, then steam until done.' }, - ], - rating: { average: 4.9, count: 204 }, - saveCount: 45, - visibility: 'public', - isSaved: true, - isCreatedByCurrentUser: false, - createdAt: '2026-08-12T12:00:00Z', - updatedAt: '2026-09-20T15:00:00Z', - }, - { - id: 'vegetable-tacos', - title: 'Roasted vegetable tacos', - description: - 'Colorful tacos with roasted vegetables, beans and avocado dressing.', - category: 'Dinner', - cuisine: 'Mexican', - difficulty: 'medium', - prepMinutes: 20, - cookMinutes: 25, - servings: 4, - tags: ['vegetarian', 'tacos', 'family'], - imageUrl: - 'https://www.theedgyveg.com/wp-content/uploads/2014/10/m9a4134.jpg', - author: nora, - ingredients: [ - { - id: 'tacos-tortillas', - name: 'Small tortillas', - amount: 8, - unit: 'pcs', - }, - { - id: 'tacos-beans', - name: 'Black beans', - amount: 400, - unit: 'g', - }, - { - id: 'tacos-avocado', - name: 'Avocado', - amount: 2, - unit: 'pcs', - }, - ], - instructions: [ - { step: 1, text: 'Roast the vegetables until golden.' }, - { step: 2, text: 'Warm the beans and tortillas.' }, - { step: 3, text: 'Assemble and serve with avocado dressing.' }, - ], - rating: { average: 4.4, count: 61 }, - saveCount: 12, - visibility: 'public', - isSaved: false, - isCreatedByCurrentUser: false, - createdAt: '2026-08-16T10:00:00Z', - updatedAt: '2026-08-16T10:00:00Z', - }, - { - id: 'norwegian-waffles', - title: 'Norwegian heart waffles', - description: - 'Soft Norwegian waffles served with brown cheese, jam or sour cream.', - category: 'Dessert', - cuisine: 'Norwegian', - difficulty: 'easy', - prepMinutes: 10, - cookMinutes: 20, - servings: 6, - tags: ['waffles', 'dessert', 'norwegian'], - imageUrl: - 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSPqyyC6kO12Vo2c05OjkMPLHs9mCOY5IQB0FmL4mraqg&s', - author: emma, - ingredients: [ - { - id: 'waffles-flour', - name: 'Wheat flour', - amount: 400, - unit: 'g', - }, - { - id: 'waffles-milk', - name: 'Milk', - amount: 600, - unit: 'ml', - }, - { - id: 'waffles-eggs', - name: 'Eggs', - amount: 3, - unit: 'pcs', - }, - ], - instructions: [ - { step: 1, text: 'Whisk the ingredients into a smooth batter.' }, - { step: 2, text: 'Let the batter rest for ten minutes.' }, - { step: 3, text: 'Cook in a greased waffle iron.' }, - ], - rating: { average: 4.7, count: 143 }, - saveCount: 44, - visibility: 'public', - isSaved: true, - isCreatedByCurrentUser: false, - createdAt: '2026-08-20T08:30:00Z', - updatedAt: '2026-08-20T08:30:00Z', - }, - { - id: 'sheet-pan-vegetables', - title: - 'Extra colorful sheet-pan vegetables with crispy chickpeas and lemon tahini dressing', - description: - 'A long-title example with roasted seasonal vegetables and chickpeas.', - category: 'Dinner', - cuisine: 'Mediterranean', - difficulty: 'medium', - prepMinutes: 25, - cookMinutes: 40, - servings: 4, - tags: [ - 'vegan', - 'gluten-free', - 'high-protein', - 'meal-prep', - 'vegetables', - 'weeknight', - ], - imageUrl: - 'https://www.veganricha.com/wp-content/uploads/2022/03/Mediterranean-Veggie-Bowl-1277-e1648603282208.jpg', - author: nora, - ingredients: [ - { - id: 'sheet-pan-chickpeas', - name: 'Chickpeas', - amount: 400, - unit: 'g', - }, - { - id: 'sheet-pan-vegetables', - name: 'Mixed vegetables', - amount: 800, - unit: 'g', - }, - { - id: 'sheet-pan-tahini', - name: 'Tahini', - amount: 3, - unit: 'tbsp', - }, - ], - instructions: [ - { step: 1, text: 'Cut the vegetables into even pieces.' }, - { step: 2, text: 'Roast vegetables and chickpeas until crisp.' }, - { step: 3, text: 'Serve with lemon tahini dressing.' }, - ], - rating: { average: 4.3, count: 28 }, - saveCount: 0, - visibility: 'public', - isSaved: false, - isCreatedByCurrentUser: false, - createdAt: '2026-08-22T13:00:00Z', - updatedAt: '2026-09-01T12:00:00Z', - }, - { - id: 'tomato-soup', - title: 'Simple tomato soup', - description: - 'A simple tomato soup used to demonstrate a missing recipe image.', - category: 'Soup', - cuisine: 'European', - difficulty: 'easy', - prepMinutes: 5, - cookMinutes: 25, - servings: 4, - tags: ['soup', 'quick', 'vegetarian'], - imageUrl: null, - author: currentUser, - ingredients: [ - { - id: 'tomato-soup-tomatoes', - name: 'Canned tomatoes', - amount: 800, - unit: 'g', - }, - { - id: 'tomato-soup-stock', - name: 'Vegetable stock', - amount: 500, - unit: 'ml', - }, - ], - instructions: [ - { step: 1, text: 'Simmer tomatoes and stock for twenty minutes.' }, - { step: 2, text: 'Blend until smooth and season to taste.' }, - ], - rating: { average: 0, count: 0 }, - saveCount: 11, - visibility: 'private', - isSaved: false, - isCreatedByCurrentUser: true, - createdAt: '2026-08-24T17:00:00Z', - updatedAt: '2026-08-24T17:00:00Z', - }, - { - id: 'falafel-bowl', - title: 'Falafel bowl with hummus', - description: - 'Crispy falafel served with hummus, fresh salad and warm flatbread.', - category: 'Lunch', - cuisine: 'Middle Eastern', - difficulty: 'medium', - prepMinutes: 25, - cookMinutes: 20, - servings: 4, - tags: ['vegetarian', 'lunch', 'protein'], - imageUrl: - 'https://spicecravings.com/wp-content/uploads/2022/07/falafel-salad-47.jpg', - author: yusuf, - ingredients: [ - { - id: 'falafel-chickpeas', - name: 'Chickpeas', - amount: 500, - unit: 'g', - }, - { - id: 'falafel-hummus', - name: 'Hummus', - amount: 250, - unit: 'g', - }, - { - id: 'falafel-salad', - name: 'Mixed salad', - amount: 300, - unit: 'g', - }, - ], - instructions: [ - { step: 1, text: 'Shape and cook the falafel.' }, - { step: 2, text: 'Prepare the salad and warm the flatbread.' }, - { step: 3, text: 'Arrange everything in serving bowls.' }, - ], - rating: { average: 4.7, count: 95 }, - saveCount: 3353, - visibility: 'public', - isSaved: true, - isCreatedByCurrentUser: false, - createdAt: '2026-08-26T11:30:00Z', - updatedAt: '2026-08-26T11:30:00Z', - }, - { - id: 'apple-cake', - title: 'Norwegian apple cake', - description: - 'A soft cinnamon cake topped with thin apple slices and sugar.', - category: 'Dessert', - cuisine: 'Norwegian', - difficulty: 'medium', - prepMinutes: 20, - cookMinutes: 45, - servings: 8, - tags: ['cake', 'apple', 'baking'], - imageUrl: - 'https://ohsweetbasil.com/wp-content/uploads/old-fashioned-apple-cake-with-warm-caramel-sauce-recipe-12.jpg', - author: currentUser, - ingredients: [ - { - id: 'apple-cake-apples', - name: 'Apples', - amount: 3, - unit: 'pcs', - }, - { - id: 'apple-cake-flour', - name: 'Wheat flour', - amount: 250, - unit: 'g', - }, - { - id: 'apple-cake-butter', - name: 'Butter', - amount: 150, - unit: 'g', - }, - ], - instructions: [ - { step: 1, text: 'Prepare the cake batter.' }, - { step: 2, text: 'Add sliced apples and cinnamon.' }, - { step: 3, text: 'Bake until golden and cooked through.' }, - ], - rating: { average: 4.6, count: 19 }, - saveCount: 35, - visibility: 'public', - isSaved: false, - isCreatedByCurrentUser: true, - createdAt: '2026-08-28T15:00:00Z', - updatedAt: '2026-09-05T16:00:00Z', - }, - { - id: 'thai-green-curry', - title: 'Thai green curry', - description: - 'A fragrant coconut curry with vegetables, basil and green curry paste.', - category: 'Dinner', - cuisine: 'Thai', - difficulty: 'medium', - prepMinutes: 20, - cookMinutes: 30, - servings: 4, - tags: ['curry', 'spicy', 'dairy-free'], - imageUrl: - 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTHnXI31TDQNX8FSjx1Swz_Tso_W2WPyLne0YgokB4GGPGPvMV3QsiUg7Q&s=10', - author: nora, - ingredients: [ - { - id: 'thai-curry-coconut', - name: 'Coconut milk', - amount: 400, - unit: 'ml', - }, - { - id: 'thai-curry-paste', - name: 'Green curry paste', - amount: 2, - unit: 'tbsp', - }, - { - id: 'thai-curry-vegetables', - name: 'Mixed vegetables', - amount: 500, - unit: 'g', - }, - ], - instructions: [ - { step: 1, text: 'Fry the curry paste until fragrant.' }, - { step: 2, text: 'Add coconut milk and vegetables.' }, - { step: 3, text: 'Simmer until tender and finish with basil.' }, - ], - rating: { average: 4.5, count: 73 }, - saveCount: 35, - visibility: 'public', - isSaved: false, - isCreatedByCurrentUser: false, - createdAt: '2026-09-01T10:00:00Z', - updatedAt: '2026-09-01T10:00:00Z', - }, - { - id: 'lamb-stew', - title: 'Slow-cooked lamb and vegetable stew', - description: - 'A rich lamb stew developed as a private recipe for future editing.', - category: 'Dinner', - cuisine: 'International', - difficulty: 'hard', - prepMinutes: 30, - cookMinutes: 150, - servings: 6, - tags: ['lamb', 'slow-cooked', 'comfort-food'], - imageUrl: - 'https://autoimmunewellness.com/wp-content/uploads/2017/01/batch_Hearty-Irish-Lamb-Stew-lscape.jpg', - author: currentUser, - ingredients: [ - { - id: 'lamb-stew-lamb', - name: 'Lamb shoulder', - amount: 1, - unit: 'kg', - }, - { - id: 'lamb-stew-potatoes', - name: 'Potatoes', - amount: 600, - unit: 'g', - }, - { - id: 'lamb-stew-carrots', - name: 'Carrots', - amount: 4, - unit: 'pcs', - }, - ], - instructions: [ - { step: 1, text: 'Brown the lamb in batches.' }, - { step: 2, text: 'Add vegetables, stock and seasoning.' }, - { step: 3, text: 'Cook slowly until the lamb is tender.' }, - ], - rating: { average: 0, count: 0 }, - saveCount: 466, - visibility: 'private', - isSaved: false, - isCreatedByCurrentUser: true, - createdAt: '2026-09-03T18:00:00Z', - updatedAt: '2026-09-03T18:00:00Z', - }, - { - id: 'ultimate-double-cheeseburger', - title: - 'Ultimate Double Cheeseburger with Caramelized Onions, Crispy Bacon and Homemade Burger Sauce', - description: - 'A generously stacked homemade cheeseburger with two juicy beef patties, melted cheddar, crispy bacon, slow-caramelized onions, fresh vegetables and a tangy homemade burger sauce. This recipe is designed as a more detailed test case for the recipe detail page, with a longer title, richer description, more tags, a larger ingredient list and a more complete set of instructions.', - category: 'Dinner', - cuisine: 'American', - difficulty: 'medium', - prepMinutes: 35, - cookMinutes: 30, - servings: 4, - tags: [ - 'burger', - 'beef', - 'cheeseburger', - 'bacon', - 'comfort-food', - 'homemade', - 'weekend', - 'grill', - ], - imageUrl: - 'https://ohsweetbasil.com/wp-content/uploads/how-to-grill-a-perfect-burger-recipe-what-ground-beef-to-buy-6-900x600.jpg', - author: currentUser, - ingredients: [ - { - id: 'ultimate-burger-ground-beef', - name: 'Ground beef', - amount: 800, - unit: 'g', - note: 'Preferably 15–20% fat', - }, - { - id: 'ultimate-burger-buns', - name: 'Burger buns', - amount: 4, - unit: 'pcs', - note: 'Brioche or potato buns work well', - }, - { - id: 'ultimate-burger-cheddar', - name: 'Cheddar cheese', - amount: 8, - unit: 'slices', - }, - { - id: 'ultimate-burger-bacon', - name: 'Bacon', - amount: 8, - unit: 'slices', - }, - { - id: 'ultimate-burger-onions', - name: 'Yellow onions', - amount: 2, - unit: 'pcs', - note: 'Thinly sliced', - }, - { - id: 'ultimate-burger-butter', - name: 'Butter', - amount: 20, - unit: 'g', - }, - { - id: 'ultimate-burger-lettuce', - name: 'Crisp lettuce', - amount: 4, - unit: 'leaves', - }, - { - id: 'ultimate-burger-tomato', - name: 'Tomato', - amount: 1, - unit: 'pcs', - note: 'Sliced', - }, - { - id: 'ultimate-burger-pickles', - name: 'Pickles', - amount: 12, - unit: 'slices', - }, - { - id: 'ultimate-burger-mayonnaise', - name: 'Mayonnaise', - amount: 80, - unit: 'g', - }, - { - id: 'ultimate-burger-ketchup', - name: 'Ketchup', - amount: 40, - unit: 'g', - }, - { - id: 'ultimate-burger-mustard', - name: 'Dijon mustard', - amount: 20, - unit: 'g', - }, - { - id: 'ultimate-burger-pickle-juice', - name: 'Pickle juice', - amount: 10, - unit: 'ml', - note: 'Optional, for the burger sauce', - }, - { - id: 'ultimate-burger-salt', - name: 'Salt', - amount: 1.5, - unit: 'tsp', - }, - { - id: 'ultimate-burger-pepper', - name: 'Black pepper', - amount: 1, - unit: 'tsp', - note: 'Freshly ground', - }, - ], - instructions: [ - { - step: 1, - text: 'Prepare the burger sauce by mixing the mayonnaise, ketchup, Dijon mustard and pickle juice in a small bowl. Refrigerate until the burgers are ready to assemble.', - }, - { - step: 2, - text: 'Melt the butter in a skillet over medium-low heat. Add the sliced onions and cook slowly for 15–20 minutes, stirring regularly, until deeply golden, soft and caramelized.', - }, - { - step: 3, - text: 'While the onions cook, fry the bacon in a separate skillet until crisp. Transfer it to a plate lined with paper towel and set aside.', - }, - { - step: 4, - text: 'Divide the ground beef into eight equal portions and gently shape them into thin patties slightly wider than the burger buns. Avoid pressing or compacting the meat too firmly.', - }, - { - step: 5, - text: 'Season both sides of the patties with salt and freshly ground black pepper just before cooking.', - }, - { - step: 6, - text: 'Heat a large skillet, griddle or grill over high heat. Cook the patties in batches for about 2–3 minutes on the first side, then flip and cook for another 1–2 minutes.', - }, - { - step: 7, - text: 'Place one slice of cheddar on each patty during the final minute of cooking. Allow the cheese to melt, then stack two patties together for each burger.', - }, - { - step: 8, - text: 'Lightly toast the burger buns cut-side down in the skillet or on the grill until golden around the edges.', - }, - { - step: 9, - text: 'Spread burger sauce over both sides of each toasted bun. Add lettuce and tomato to the bottom bun, followed by the double cheeseburger patties.', - }, - { - step: 10, - text: 'Top each burger with crispy bacon, caramelized onions and pickle slices. Add a little extra burger sauce if desired, then finish with the top bun and serve immediately.', - }, - ], - rating: { average: 4.7, count: 138 }, - saveCount: 924, - visibility: 'public', - isSaved: false, - isCreatedByCurrentUser: true, - createdAt: '2026-09-18T16:30:00Z', - updatedAt: '2026-10-08T19:15:00Z', - }, -]; diff --git a/apps/web/src/features/cookbook/mockCookbookQuery.test.ts b/apps/web/src/features/cookbook/mockCookbookQuery.test.ts deleted file mode 100644 index b6fa507..0000000 --- a/apps/web/src/features/cookbook/mockCookbookQuery.test.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { recipes } from '../../data/recipes'; -const INITIAL_SAVED_RECIPE_IDS = recipes - .filter((recipe) => recipe.isSaved) - .map((recipe) => recipe.id); - -import { getMockCookbookResult, type CookbookQuery } from './mockCookbookQuery'; - -function createQuery(overrides: Partial = {}): CookbookQuery { - return { - scope: 'all', - search: '', - savedRecipeIds: INITIAL_SAVED_RECIPE_IDS, - category: null, - maxCookingMinutes: null, - sort: 'recently-updated', - page: 1, - pageSize: 50, - ...overrides, - }; -} - -describe('getMockCookbookResult', () => { - it('returns the union of saved and created recipes for All', () => { - const result = getMockCookbookResult(createQuery()); - - expect(result.totalItems).toBe(9); - - expect( - result.items.every( - (recipe) => - recipe.isCreatedByCurrentUser || - INITIAL_SAVED_RECIPE_IDS.includes(recipe.id), - ), - ).toBe(true); - }); - - it('returns only runtime saved recipes for Saved', () => { - const result = getMockCookbookResult( - createQuery({ - scope: 'saved', - savedRecipeIds: ['salmon-pasta'], - }), - ); - - expect(result.items.map((recipe) => recipe.id)).toEqual(['salmon-pasta']); - }); - - it('returns only current-user recipes for Created', () => { - const result = getMockCookbookResult( - createQuery({ - scope: 'created', - }), - ); - - expect(result.items.every((recipe) => recipe.isCreatedByCurrentUser)).toBe( - true, - ); - }); - - it('includes current-user private recipes in Created', () => { - const result = getMockCookbookResult( - createQuery({ - scope: 'created', - }), - ); - - expect(result.items.map((recipe) => recipe.id)).toEqual( - expect.arrayContaining(['tomato-soup', 'lamb-stew']), - ); - }); - - it('uses the same ingredient search behavior as Explore', () => { - const result = getMockCookbookResult( - createQuery({ - search: 'red lentils', - }), - ); - - expect(result.items.map((recipe) => recipe.id)).toContain('lentil-soup'); - }); - - it('filters by category', () => { - const result = getMockCookbookResult( - createQuery({ - category: 'dinner', - }), - ); - - expect(result.items.every((recipe) => recipe.category === 'Dinner')).toBe( - true, - ); - }); - - it('filters by maximum cooking time', () => { - const result = getMockCookbookResult( - createQuery({ - maxCookingMinutes: 30, - }), - ); - - expect( - result.items.every( - (recipe) => recipe.prepMinutes + recipe.cookMinutes <= 30, - ), - ).toBe(true); - }); - - it('sorts recently updated by updatedAt descending', () => { - const result = getMockCookbookResult( - createQuery({ - sort: 'recently-updated', - }), - ); - - for (let index = 1; index < result.items.length; index += 1) { - const previous = result.items[index - 1]; - const current = result.items[index]; - - if (!previous || !current) { - continue; - } - - expect(Date.parse(previous.updatedAt)).toBeGreaterThanOrEqual( - Date.parse(current.updatedAt), - ); - } - }); - - it('sorts cooking time shortest first', () => { - const result = getMockCookbookResult( - createQuery({ - sort: 'cooking-time', - }), - ); - - for (let index = 1; index < result.items.length; index += 1) { - const previous = result.items[index - 1]; - const current = result.items[index]; - - if (!previous || !current) { - continue; - } - - const previousMinutes = previous.prepMinutes + previous.cookMinutes; - const currentMinutes = current.prepMinutes + current.cookMinutes; - - expect(previousMinutes).toBeLessThanOrEqual(currentMinutes); - } - }); - - it('sorts alphabetically', () => { - const result = getMockCookbookResult( - createQuery({ - sort: 'alphabetical', - }), - ); - - const titles = result.items.map((recipe) => recipe.title); - - expect(titles).toEqual([...titles].sort((a, b) => a.localeCompare(b))); - }); - - it('paginates after scope, filtering, and sorting', () => { - const firstPage = getMockCookbookResult( - createQuery({ - page: 1, - pageSize: 6, - }), - ); - - const secondPage = getMockCookbookResult( - createQuery({ - page: 2, - pageSize: 6, - }), - ); - - expect(firstPage.totalItems).toBe(9); - expect(firstPage.items).toHaveLength(6); - expect(secondPage.items).toHaveLength(3); - }); -}); diff --git a/apps/web/src/features/cookbook/mockCookbookQuery.ts b/apps/web/src/features/cookbook/mockCookbookQuery.ts deleted file mode 100644 index 1de2226..0000000 --- a/apps/web/src/features/cookbook/mockCookbookQuery.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { recipes } from '../../data/recipes'; -import { paginate, type PageResult } from '../../lib/pagination/paginate'; -import { - filterRecipesByBrowseCriteria, - getRecipeTotalMinutes, - type RecipeQueryFilters, -} from '../../lib/recipeBrowse/recipeBrowse'; -import type { Recipe } from '../../types/recipe'; - -import type { CookbookScope } from './cookbookBrowseState'; - -type CookbookSort = - | 'newest' - | 'recently-updated' - | 'cooking-time' - | 'alphabetical'; - -export type CookbookQuery = RecipeQueryFilters & { - scope: CookbookScope; - search: string; - savedRecipeIds: readonly string[]; - sort: CookbookSort; - page: number; - pageSize: number; -}; - -export type CookbookResult = PageResult; - -function compareRecentlyUpdated(a: Recipe, b: Recipe) { - const dateDifference = Date.parse(b.updatedAt) - Date.parse(a.updatedAt); - - if (dateDifference !== 0) { - return dateDifference; - } - - return a.title.localeCompare(b.title); -} - -function compareCookingTime(a: Recipe, b: Recipe) { - const timeDifference = getRecipeTotalMinutes(a) - getRecipeTotalMinutes(b); - - if (timeDifference !== 0) { - return timeDifference; - } - - return compareRecentlyUpdated(a, b); -} - -function compareAlphabetical(a: Recipe, b: Recipe) { - const titleDifference = a.title.localeCompare(b.title); - - if (titleDifference !== 0) { - return titleDifference; - } - - return compareRecentlyUpdated(a, b); -} - -const sortComparators: Record number> = - { - newest: (a, b) => - Date.parse(b.createdAt) - Date.parse(a.createdAt) || - b.id.localeCompare(a.id), - 'recently-updated': compareRecentlyUpdated, - 'cooking-time': compareCookingTime, - alphabetical: compareAlphabetical, - }; - -function sortRecipes(items: readonly Recipe[], sort: CookbookSort) { - return [...items].sort(sortComparators[sort]); -} - -export function getMockCookbookResult({ - scope, - search, - savedRecipeIds, - category, - maxCookingMinutes, - sort, - page, - pageSize, -}: CookbookQuery): CookbookResult { - const savedIds = new Set(savedRecipeIds); - - const scopedRecipes = recipes.filter((recipe) => { - const isSaved = savedIds.has(recipe.id); - const isCreated = recipe.isCreatedByCurrentUser; - - switch (scope) { - case 'saved': - return isSaved; - - case 'created': - return isCreated; - - case 'all': - return isSaved || isCreated; - } - }); - - const filteredRecipes = filterRecipesByBrowseCriteria(scopedRecipes, { - search, - category, - maxCookingMinutes, - }); - - const sortedRecipes = sortRecipes(filteredRecipes, sort); - - return paginate(sortedRecipes, page, pageSize); -} diff --git a/apps/web/src/features/explore/mockExploreQuery.test.ts b/apps/web/src/features/explore/mockExploreQuery.test.ts deleted file mode 100644 index 674fa26..0000000 --- a/apps/web/src/features/explore/mockExploreQuery.test.ts +++ /dev/null @@ -1,271 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { - getMockExploreResult, - MOCK_EXPLORE_NOW, - type ExploreQuery, -} from './mockExploreQuery'; - -function createQuery(overrides: Partial = {}): ExploreQuery { - return { - search: '', - category: null, - maxCookingMinutes: null, - sort: 'popular', - page: 1, - pageSize: 50, - ...overrides, - }; -} - -describe('getMockExploreResult', () => { - it('only returns public recipes', () => { - const result = getMockExploreResult(createQuery()); - - expect(result.items.every((recipe) => recipe.visibility === 'public')).toBe( - true, - ); - }); - - it('searches titles and descriptions case-insensitively', () => { - const result = getMockExploreResult( - createQuery({ - search: 'SALMON', - }), - ); - - expect(result.items.map((recipe) => recipe.id)).toContain('salmon-pasta'); - }); - - it('searches ingredient names', () => { - const result = getMockExploreResult( - createQuery({ - search: 'salmon fillet', - }), - ); - - expect(result.items.map((recipe) => recipe.id)).toContain('salmon-pasta'); - }); - - it('searches tags and treats hyphens like spaces', () => { - const result = getMockExploreResult( - createQuery({ - search: 'one pan', - }), - ); - - expect(result.items.map((recipe) => recipe.id)).toContain('shakshuka'); - }); - - it('filters by category before pagination', () => { - const result = getMockExploreResult( - createQuery({ - category: 'dinner', - page: 2, - pageSize: 2, - }), - ); - - expect(result.totalItems).toBe(6); - expect(result.items).toHaveLength(2); - - expect(result.items.every((recipe) => recipe.category === 'Dinner')).toBe( - true, - ); - }); - - it('supports the 15-minute maximum', () => { - const result = getMockExploreResult( - createQuery({ - maxCookingMinutes: 15, - }), - ); - - expect( - result.items.every( - (recipe) => recipe.prepMinutes + recipe.cookMinutes <= 15, - ), - ).toBe(true); - }); - - it('supports the 30-minute maximum', () => { - const result = getMockExploreResult( - createQuery({ - maxCookingMinutes: 30, - }), - ); - - expect(result.totalItems).toBe(2); - - expect( - result.items.every( - (recipe) => recipe.prepMinutes + recipe.cookMinutes <= 30, - ), - ).toBe(true); - }); - - it('supports the 60-minute maximum', () => { - const result = getMockExploreResult( - createQuery({ - maxCookingMinutes: 60, - }), - ); - - expect(result.totalItems).toBe(7); - - expect( - result.items.every( - (recipe) => recipe.prepMinutes + recipe.cookMinutes <= 60, - ), - ).toBe(true); - }); - - it('supports a custom maximum cooking time', () => { - const result = getMockExploreResult( - createQuery({ - maxCookingMinutes: 45, - }), - ); - - expect( - result.items.every( - (recipe) => recipe.prepMinutes + recipe.cookMinutes <= 45, - ), - ).toBe(true); - }); - - it('makes larger maximum-time presets cumulative', () => { - const under15 = getMockExploreResult( - createQuery({ - maxCookingMinutes: 15, - }), - ); - - const under30 = getMockExploreResult( - createQuery({ - maxCookingMinutes: 30, - }), - ); - - const under60 = getMockExploreResult( - createQuery({ - maxCookingMinutes: 60, - }), - ); - - expect(under30.totalItems).toBeGreaterThanOrEqual(under15.totalItems); - - expect(under60.totalItems).toBeGreaterThanOrEqual(under30.totalItems); - }); - - it('sorts Most popular using rating average and rating count', () => { - const result = getMockExploreResult( - createQuery({ - sort: 'popular', - }), - ); - - expect(result.items.slice(0, 3).map((recipe) => recipe.id)).toEqual([ - 'chicken-biryani', - 'norwegian-waffles', - 'shakshuka', - ]); - }); - - it('limits Trending to the previous 14 days and ranks by popularity', () => { - const result = getMockExploreResult( - createQuery({ - sort: 'trending', - }), - ); - - const now = Date.parse(MOCK_EXPLORE_NOW); - const cutoff = now - 14 * 24 * 60 * 60 * 1000; - - expect( - result.items.every((recipe) => { - const createdAt = Date.parse(recipe.createdAt); - - return createdAt >= cutoff && createdAt <= now; - }), - ).toBe(true); - - expect(result.items.map((recipe) => recipe.id)).toEqual([ - 'falafel-bowl', - 'thai-green-curry', - 'sheet-pan-vegetables', - 'apple-cake', - ]); - }); - - it('sorts Newest by creation date descending', () => { - const result = getMockExploreResult( - createQuery({ - sort: 'newest', - }), - ); - - expect(result.items.slice(0, 3).map((recipe) => recipe.id)).toEqual([ - 'ultimate-double-cheeseburger', - 'thai-green-curry', - 'apple-cake', - ]); - }); - - it('sorts Most saved by aggregate save count', () => { - const result = getMockExploreResult( - createQuery({ - sort: 'most-saved', - }), - ); - - for (let index = 1; index < result.items.length; index += 1) { - const previous = result.items[index - 1]; - const current = result.items[index]; - - if (!previous || !current) { - continue; - } - - expect(previous.saveCount).toBeGreaterThanOrEqual(current.saveCount); - } - }); - - it('paginates only after filtering and sorting', () => { - const firstPage = getMockExploreResult( - createQuery({ - sort: 'popular', - page: 1, - pageSize: 6, - }), - ); - - const secondPage = getMockExploreResult( - createQuery({ - sort: 'popular', - page: 2, - pageSize: 6, - }), - ); - - expect(firstPage.totalItems).toBe(11); - expect(firstPage.items).toHaveLength(6); - expect(secondPage.items).toHaveLength(5); - - expect(firstPage.items[0]?.id).not.toBe(secondPage.items[0]?.id); - }); - - it('returns no items when the combined query has no matches', () => { - const result = getMockExploreResult( - createQuery({ - search: 'definitely-not-a-recipe', - category: 'dinner', - }), - ); - - expect(result.items).toEqual([]); - expect(result.totalItems).toBe(0); - expect(result.pageCount).toBe(0); - expect(result.page).toBe(1); - }); -}); diff --git a/apps/web/src/features/explore/mockExploreQuery.ts b/apps/web/src/features/explore/mockExploreQuery.ts deleted file mode 100644 index 0c0bc24..0000000 --- a/apps/web/src/features/explore/mockExploreQuery.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { recipes } from '../../data/recipes'; -import { paginate, type PageResult } from '../../lib/pagination/paginate'; -import { filterRecipesByBrowseCriteria } from '../../lib/recipeBrowse/recipeBrowse'; -import type { Recipe } from '../../types/recipe'; - -import type { ExploreCategory } from './exploreBrowseState'; - -type ExploreSort = 'trending' | 'popular' | 'newest' | 'most-saved'; - -export type ExploreQuery = { - search: string; - category: Exclude | null; - maxCookingMinutes: number | null; - sort: ExploreSort; - page: number; - pageSize: number; -}; - -export type ExploreResult = PageResult; - -/** - * The mock catalog represents a fixed Delivery 1 snapshot. - * - * Trending therefore uses a fixed reference time instead of the real system - * clock. Otherwise the static recipes would eventually all become older than - * the 14-day trending window. - */ -export const MOCK_EXPLORE_NOW = '2026-09-05T12:00:00Z'; - -const MOCK_EXPLORE_NOW_MS = Date.parse(MOCK_EXPLORE_NOW); -const TRENDING_WINDOW_MS = 14 * 24 * 60 * 60 * 1000; - -export function getPopularityScore(recipe: Recipe) { - return recipe.rating.average * Math.log1p(recipe.rating.count); -} - -function compareNewest(a: Recipe, b: Recipe) { - const dateDifference = Date.parse(b.createdAt) - Date.parse(a.createdAt); - - if (dateDifference !== 0) { - return dateDifference; - } - - return a.id.localeCompare(b.id); -} - -function comparePopular(a: Recipe, b: Recipe) { - const popularityDifference = getPopularityScore(b) - getPopularityScore(a); - - if (popularityDifference !== 0) { - return popularityDifference; - } - - const ratingCountDifference = b.rating.count - a.rating.count; - - if (ratingCountDifference !== 0) { - return ratingCountDifference; - } - - const ratingAverageDifference = b.rating.average - a.rating.average; - - if (ratingAverageDifference !== 0) { - return ratingAverageDifference; - } - - return compareNewest(a, b); -} - -function compareMostSaved(a: Recipe, b: Recipe) { - const saveCountDifference = b.saveCount - a.saveCount; - - if (saveCountDifference !== 0) { - return saveCountDifference; - } - - return comparePopular(a, b); -} - -function isTrendingRecipe(recipe: Recipe) { - const createdAt = Date.parse(recipe.createdAt); - - if (!Number.isFinite(createdAt)) { - return false; - } - - const trendingWindowStart = MOCK_EXPLORE_NOW_MS - TRENDING_WINDOW_MS; - - return createdAt >= trendingWindowStart && createdAt <= MOCK_EXPLORE_NOW_MS; -} - -const sortComparators: Record number> = { - trending: comparePopular, - popular: comparePopular, - newest: compareNewest, - 'most-saved': compareMostSaved, -}; - -function sortRecipes(items: readonly Recipe[], sort: ExploreSort) { - return [...items].sort(sortComparators[sort]); -} - -export function getMockExploreResult({ - search, - category, - maxCookingMinutes, - sort, - page, - pageSize, -}: ExploreQuery): ExploreResult { - const publicRecipes = recipes.filter( - (recipe) => recipe.visibility === 'public', - ); - - const filteredRecipes = filterRecipesByBrowseCriteria(publicRecipes, { - search, - category, - maxCookingMinutes, - }); - - const sortCandidates = - sort === 'trending' - ? filteredRecipes.filter(isTrendingRecipe) - : filteredRecipes; - - const sortedRecipes = sortRecipes(sortCandidates, sort); - - return paginate(sortedRecipes, page, pageSize); -} diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx index 71ef56c..6210d89 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx @@ -1,4 +1,4 @@ -import { useCallback, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { useLocation, useNavigate, useParams } from 'react-router-dom'; @@ -100,6 +100,13 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { const currentUser = useAppStore((state) => state.currentUser); const busyRef = useRef(false); + const mounted = useRef(true); + useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); const [busy, setBusy] = useState(false); const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false); const [selectedServings, setSelectedServings] = useState(recipe.servings); @@ -169,10 +176,17 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { } function openRating() { + setFeedback(null); setPendingRating(recipe.userRating ?? 0); setRatingOpen(true); } + function closeRating() { + if (busy) return; + setRatingOpen(false); + setFeedback(null); + } + async function performAction(action: () => Promise, message: string) { if (busyRef.current) return; busyRef.current = true; @@ -180,8 +194,11 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { setFeedback(null); try { await action(); + if (!mounted.current) return; + setRatingOpen(false); setFeedback({ tone: 'success', title: 'Recipe updated', message }); } catch (error) { + if (!mounted.current) return; setFeedback({ tone: 'error', title: 'Unable to update recipe', @@ -189,7 +206,7 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { }); } finally { busyRef.current = false; - setBusy(false); + if (mounted.current) setBusy(false); } } function handleSaveClick() { @@ -628,9 +645,7 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { open={ratingOpen} title="Rate this recipe" description="Choose a rating from 1 to 5 stars." - onClose={() => { - if (!busy) setRatingOpen(false); - }} + onClose={closeRating} footer={ <> {recipe.userRating != null && ( @@ -647,11 +662,7 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { Remove rating )} - ); diff --git a/apps/web/src/features/recipes/recipeImages.test.ts b/apps/web/src/features/recipes/recipeImages.test.ts new file mode 100644 index 0000000..9331d74 --- /dev/null +++ b/apps/web/src/features/recipes/recipeImages.test.ts @@ -0,0 +1,27 @@ +import { afterEach, expect, it, vi } from 'vitest'; +import { uploadRecipeImage } from './recipeImages'; +afterEach(() => vi.unstubAllGlobals()); +it.each([ + new Response('proxy error'), + Response.json({}), + Response.json({ imageUrl: 'https://other.example/image.jpg' }), +])( + 'rejects malformed upload responses with a usable error', + async (response) => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => response), + ); + await expect( + uploadRecipeImage(new Blob(['image'], { type: 'image/png' })), + ).rejects.toThrow('Unable to upload the image. Please try again.'); + }, +); +it('checks the encoded size before making a request', async () => { + const fetch = vi.fn(); + vi.stubGlobal('fetch', fetch); + await expect( + uploadRecipeImage(new Blob([new Uint8Array(5 * 1024 * 1024 + 1)])), + ).rejects.toThrow('up to 5 MB'); + expect(fetch).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/features/recipes/recipeImages.ts b/apps/web/src/features/recipes/recipeImages.ts index bb9716e..2d4a755 100644 --- a/apps/web/src/features/recipes/recipeImages.ts +++ b/apps/web/src/features/recipes/recipeImages.ts @@ -1,29 +1,46 @@ export async function uploadRecipeImage(image: Blob): Promise { if (image.size > 5 * 1024 * 1024) throw new Error('Choose an image up to 5 MB.'); - const response = await fetch( - import.meta.env.DEV ? '/uploads' : '/project2/api/uploads', - { - method: 'POST', - credentials: 'same-origin', - headers: { - 'Content-Type': image.type, - 'X-Requested-With': 'recipe-platform', + let response: Response; + try { + response = await fetch( + import.meta.env.DEV ? '/uploads' : '/project2/api/uploads', + { + method: 'POST', + credentials: 'same-origin', + headers: { + 'Content-Type': image.type, + 'X-Requested-With': 'recipe-platform', + }, + body: image, }, - body: image, - }, - ); + ); + } catch { + throw new Error('Unable to connect. Please try uploading again.'); + } + const failure = 'Unable to upload the image. Please try again.'; if (!response.ok) { const messages: Record = { 401: 'Please sign in to upload an image.', - 413: 'Choose an image up to 5 MB.', + 413: 'Image size or storage limit exceeded.', 415: 'Choose a valid JPG, PNG, or WebP image.', + 429: 'Too many uploads. Try again in an hour.', + 507: 'Image storage is full. Please try again later.', }; - throw new Error( - messages[response.status] ?? - 'Unable to upload the image. Please try again.', - ); + throw new Error(messages[response.status] ?? failure); + } + try { + const result: unknown = await response.json(); + if ( + !result || + typeof result !== 'object' || + !('imageUrl' in result) || + typeof result.imageUrl !== 'string' || + !/^\/uploads\/[0-9a-f-]+\.(jpg|png|webp)$/.test(result.imageUrl) + ) + throw new Error(); + return result.imageUrl; + } catch { + throw new Error(failure); } - const result: { imageUrl: string } = await response.json(); - return result.imageUrl; } diff --git a/apps/web/src/features/recipes/useRecipeQuery.test.tsx b/apps/web/src/features/recipes/useRecipeQuery.test.tsx new file mode 100644 index 0000000..9f7cf93 --- /dev/null +++ b/apps/web/src/features/recipes/useRecipeQuery.test.tsx @@ -0,0 +1,80 @@ +import { act, renderHook, waitFor } from '@testing-library/react'; +import { beforeEach, expect, it, vi } from 'vitest'; +import { useAppStore } from '../../store'; +import { apiUser } from '../../test/recipeApiFixtures'; +import { useRecipeChanges } from './recipeApi'; +import { useRecipeQuery } from './useRecipeQuery'; + +beforeEach(() => { + useAppStore.setState({ + currentUser: apiUser, + sessionStatus: 'authenticated', + }); + useRecipeChanges.setState({ revision: 0 }); +}); +it('waits for session restoration and performs only one initial read', async () => { + useAppStore.setState({ currentUser: null, sessionStatus: 'restoring' }); + const load = vi.fn(async () => 'recipes'); + const { result } = renderHook(() => useRecipeQuery('list', load)); + expect(load).not.toHaveBeenCalled(); + expect(result.current.loading).toBe(true); + act(() => + useAppStore.setState({ + currentUser: apiUser, + sessionStatus: 'authenticated', + }), + ); + await waitFor(() => expect(result.current.data).toBe('recipes')); + expect(load).toHaveBeenCalledTimes(1); +}); +it('keeps data during refresh, reports refresh failure inline and supports retry', async () => { + let reject!: (error: Error) => void; + const load = vi + .fn<(_: AbortSignal) => Promise>() + .mockResolvedValueOnce('old') + .mockImplementationOnce( + () => + new Promise((_resolve, fail) => { + reject = fail; + }), + ) + .mockResolvedValueOnce('new'); + const { result } = renderHook(() => useRecipeQuery('list', load)); + await waitFor(() => expect(result.current.data).toBe('old')); + act(() => useRecipeChanges.setState({ revision: 1 })); + expect(result.current).toMatchObject({ + data: 'old', + loading: false, + refreshing: true, + }); + await act(async () => reject(new Error('offline'))); + expect(result.current.data).toBe('old'); + expect(result.current.error).toBeUndefined(); + expect(result.current.refreshError).toBeTruthy(); + act(() => result.current.retry()); + await waitFor(() => expect(result.current.data).toBe('new')); + expect(result.current.refreshError).toBeUndefined(); +}); +it('never retains data across user changes or accepts an aborted response', async () => { + let finish!: (value: string) => void; + const load = vi + .fn<(_: AbortSignal) => Promise>() + .mockResolvedValueOnce('first user') + .mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve; + }), + ) + .mockResolvedValueOnce('third user'); + const { result } = renderHook(() => useRecipeQuery('detail', load)); + await waitFor(() => expect(result.current.data).toBe('first user')); + act(() => + useAppStore.setState({ currentUser: { ...apiUser, id: 'second' } }), + ); + expect(result.current.data).toBeUndefined(); + act(() => useAppStore.setState({ currentUser: { ...apiUser, id: 'third' } })); + await waitFor(() => expect(result.current.data).toBe('third user')); + await act(async () => finish('stale second user')); + expect(result.current.data).toBe('third user'); +}); diff --git a/apps/web/src/features/recipes/useRecipeQuery.ts b/apps/web/src/features/recipes/useRecipeQuery.ts index 9e9f049..270b5f7 100644 --- a/apps/web/src/features/recipes/useRecipeQuery.ts +++ b/apps/web/src/features/recipes/useRecipeQuery.ts @@ -5,39 +5,53 @@ import { recipeErrorMessage, useRecipeChanges } from './recipeApi'; export function useRecipeQuery( key: string, load: (signal: AbortSignal) => Promise, + { refreshOnMutation = true } = {}, ) { const userId = useAppStore((state) => state.currentUser?.id); const sessionStatus = useAppStore((state) => state.sessionStatus); - const revision = useRecipeChanges((state) => state.revision); - const [attempt, setAttempt] = useState(0); - const requestKey = JSON.stringify([ - key, - userId, - sessionStatus, - revision, - attempt, - ]); - const [state, setState] = useState<{ key: string; data?: T; error?: string }>( - { key: '' }, + const revision = useRecipeChanges((state) => + refreshOnMutation ? state.revision : 0, ); + const [attempt, setAttempt] = useState(0); + const identity = JSON.stringify([key, userId]); + const requestKey = JSON.stringify([identity, revision, attempt]); + const waiting = sessionStatus === 'restoring'; + const [state, setState] = useState<{ + identity: string; + key: string; + hasData: boolean; + data?: T; + error?: string; + }>({ identity: '', key: '', hasData: false }); useEffect(() => { + if (waiting) return; const controller = new AbortController(); load(controller.signal).then( (data) => { - if (!controller.signal.aborted) setState({ key: requestKey, data }); + if (!controller.signal.aborted) + setState({ identity, key: requestKey, hasData: true, data }); }, (error: unknown) => { if (!controller.signal.aborted) - setState({ key: requestKey, error: recipeErrorMessage(error) }); + setState((previous) => ({ + ...(previous.identity === identity ? previous : { hasData: false }), + identity, + key: requestKey, + error: recipeErrorMessage(error), + })); }, ); return () => controller.abort(); - }, [requestKey, load]); - const current = state.key === requestKey ? state : undefined; + }, [identity, requestKey, load, waiting]); + const current = !waiting && state.identity === identity ? state : undefined; + const hasData = current?.hasData ?? false; return { - data: current?.data, - error: current?.error, - loading: !current, + data: hasData ? current?.data : undefined, + error: !hasData && current?.key === requestKey ? current.error : undefined, + refreshError: + hasData && current?.key === requestKey ? current.error : undefined, + loading: waiting || (!hasData && current?.key !== requestKey), + refreshing: hasData && current?.key !== requestKey, retry: () => setAttempt((value) => value + 1), }; } diff --git a/docs/frontend-integration.md b/docs/frontend-integration.md index 16ad844..d446312 100644 --- a/docs/frontend-integration.md +++ b/docs/frontend-integration.md @@ -21,6 +21,8 @@ - [x] Replace mock-page assertions with API integration tests. - [x] Add a real API/PostgreSQL browser test for recipe CRUD and Save/Unsave. +Review follow-up and Docker checks: [Local review test guide](review-test-guide.md). + ## Verification Run `npm run check`, `npm run test:api`, `npm run test:db` and @@ -42,8 +44,8 @@ remain available. - [ ] Verify the deployed VM flow after merge and deployment. The draft button keeps edits in the current form only. Drafts are not persisted -across navigation or reload. Mock query modules remain solely for prototype -tests and are not imported by production pages. +across navigation or reload. Obsolete prototype query modules and their tests +have been removed. ## Local rating and image checks @@ -61,7 +63,7 @@ configured PostgreSQL database and open `http://127.0.0.1:5173/project2/`. 5. Confirm that logged-out users cannot rate or upload, and that users cannot rate their own or private recipes. -Ratings use the existing table; no database migration is needed. Each user has +Ratings use the existing table. Image metadata uses the new `uploaded_images` migration. Each user has at most one rating per recipe. Removing a rating affects only that user's row. The API accepts authenticated binary uploads at `/uploads` and serves generated @@ -73,6 +75,7 @@ Images default to `uploads/` at the project root (excluded from Git). Set the absolute `UPLOAD_DIR` for a different persistent directory and make it writable by the API process. Docker uses the `recipe_images` volume, preserved by `docker compose down` and container rebuilds. Keep this volume/directory when -deploying. Image URLs are publicly readable; private recipe access does not -make image files private. Removing/replacing a recipe image changes its URL -reference; old files are retained rather than automatically deleted. +deploying. Image access follows the referencing recipes: public references allow +anonymous reads; private images require the recipe owner. Unattached files are +visible only to their uploader. Unreferenced files older than 24 hours are removed +at startup, hourly, or with `npm run images:cleanup`. See the review guide for limits. diff --git a/docs/recipe-api.md b/docs/recipe-api.md index ec265b1..b55ad25 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -2,7 +2,7 @@ Branch: `hasan/feat/recipe-crud-cookies`. API-et bruker eksisterende GraphQL Yoga og PostgreSQL-oppsett, med SQL-parametre gjennom `pg`, som autentiseringen. -Zod validerer input; databasekontrollene beholdes. Ingen ny migrasjon er nødvendig. +Zod validerer input; databasekontrollene beholdes. Bildeopplastingen bruker nå en egen migrasjon for filmetadata. ## Hurtigstart for frontend @@ -197,7 +197,7 @@ ukjente oppskrifter gir samme feil og avslører ikke private data. oppskrifter av andre brukere kan vurderes. Ny score erstatter egen tidligere vurdering. `removeRecipeRating(id)` fjerner bare egen vurdering og er idempotent. `userRating` er brukerens egen score eller null; `rating` er - oppsummert gjennomsnitt og antall. Ingen ny migrasjon er nødvendig. + oppsummert gjennomsnitt og antall. Rating bruker den eksisterende tabellen. - Frontendintegrasjonen ligger i en egen branch etter API-endringene. Separate liste-/detaljspørringer i SQL og domenefeil som oversettes til GraphQL-feil ved resolvergrensen vurderes i senere, avgrensede endringer. @@ -251,3 +251,5 @@ Passordet lagres som Argon2-hash. På Linux: `SEED_PASSWORD='...' npm run db:see AI er brukt til plananalyse, implementasjon og tester. Endringene skal gjennomgås i PR og kontrolleres med prosjektets sjekker og API-/databasetestene. + +Oppfølging etter integrasjonsreview: [Docker-testguide](review-test-guide.md). diff --git a/docs/review-test-guide.md b/docs/review-test-guide.md new file mode 100644 index 0000000..41c191f --- /dev/null +++ b/docs/review-test-guide.md @@ -0,0 +1,78 @@ +# Local review test guide + +## Start Docker + +```powershell +docker compose -f compose.dev.yaml up --build +``` + +Open **http://localhost:5173/project2/**. Startup applies the new +`uploaded_images` migration and preserves the database and image volumes. +Existing recipe image references are imported into the metadata table. +Use two accounts: an owner and a reader. + +## Browser checks + +1. **Rating without resets:** As the reader, open the owner's public recipe. + Increase servings, then save a rating. The recipe should stay visible, + servings should stay unchanged, and a success message should appear. +2. **Lists without blanking:** Save/unsave from Explore or Cookbook. The grid + should remain visible during the update, without a full-page spinner. +3. **Errors:** In browser DevTools, enable Offline and try a mutation. Expect + one error message and retained page/form data. Go online and retry. + Reopen the rating dialog: its previous error should be cleared. +4. **Edit:** Type changes without saving. Confirm that `/recipes/abc/edit` + gives an unavailable message, while another user's valid recipe gives an + ownership message. The Add Recipe form should not make a recipe-list read. +5. **User changes:** Sign out and use the other account. The previous user's + private recipes and saved state must not remain visible. +6. **Image privacy:** Upload an image to a private recipe. Copy the image URL + and open it in an incognito window: expect 404. The owner should still see + it. Make the recipe public: expect the URL to work anonymously. Make it + private again without removing the image: expect anonymous access to stop. +7. **Upload failures:** Try a non-image file or a file above 5 MB. Expect a + readable error. A valid large image is cropped/resized to at most 1600 px + on its longest edge before upload. + +An image is public only while at least one public recipe references it. +Unattached uploads are visible only to their uploader; attached private +images are visible to the recipe owner. Responses use `Cache-Control: no-store`. + +## Cleanup and limits + +```powershell +docker compose -f compose.dev.yaml exec app npm run images:cleanup +``` + +Cleanup also runs at API startup and hourly. Unreferenced files are retained +for 24 hours, then removed. Referenced images are always kept. A result of +zero for newly uploaded files is expected. + +Limits: **20 uploads/hour/user**, **100 MiB/user**, **1 GiB and 1000 files +overall**, and **5 MiB per file**. Quota checks and image attachment/cleanup +are serialized to avoid concurrent bypasses or removal during attachment. + +## Automated checks + +From the host with dependencies installed: + +```powershell +npm.cmd run check +npm.cmd run test:e2e +``` + +Against the Docker database, using isolated test schemas and temporary files: + +```powershell +docker compose -f compose.dev.yaml exec app npm run test:api +docker compose -f compose.dev.yaml exec app npm run test:db +``` + +The API tests cover privacy changes, cross-user attachment, quota limits, +legacy image migration and cleanup without touching your own recipes. +The recipe browser test needs a host-accessible `DATABASE_URL`; it explicitly +skips when none is configured. The unit tests cover failed background refresh, +session restoration, stale responses, malformed upload JSON and form retention. + +Stop with `Ctrl+C`, then `docker compose -f compose.dev.yaml down`. +Keep the volumes; `down -v` would remove local database and image data. diff --git a/e2e/recipe-api.spec.ts b/e2e/recipe-api.spec.ts index 301b6f8..b0b3268 100644 --- a/e2e/recipe-api.spec.ts +++ b/e2e/recipe-api.spec.ts @@ -162,11 +162,20 @@ test('persists recipes, uploaded images and ratings through the real API', async const reader = await readerContext.newPage(); await register(reader, 'reader@example.com'); await reader.goto(recipeUrl); + await reader.getByRole('button', { name: 'Increase servings' }).click(); await reader .getByRole('button', { name: 'Rate this recipe', exact: true }) .click(); await reader.getByRole('radio', { name: '5 stars' }).check(); await reader.getByRole('button', { name: 'Save rating' }).click(); + await expect( + reader.getByText('Rating saved.', { exact: true }), + ).toBeVisible(); + await expect( + reader + .getByRole('region', { name: 'Ingredients' }) + .getByText('3 servings', { exact: true }), + ).toBeVisible(); await expect( reader.getByRole('button', { name: 'Your rating: 5/5' }), ).toBeVisible(); diff --git a/package.json b/package.json index 0d9c093..f0a6c9e 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,8 @@ "check": "npm run format:check && npm run lint && npm run types:check && npm run db:check && npm run typecheck && npm test && npm run build", "test:db": "tsx --env-file-if-exists=.env scripts/test-database.ts", "test:api": "tsx --env-file-if-exists=.env scripts/test-recipe-api.ts", - "db:seed": "tsx --env-file-if-exists=.env apps/api/src/db/seed.ts" + "db:seed": "tsx --env-file-if-exists=.env apps/api/src/db/seed.ts", + "images:cleanup": "tsx --env-file-if-exists=.env scripts/cleanup-images.ts" }, "devDependencies": { "@eslint/js": "9.39.5", diff --git a/scripts/cleanup-images.ts b/scripts/cleanup-images.ts new file mode 100644 index 0000000..85f6c8b --- /dev/null +++ b/scripts/cleanup-images.ts @@ -0,0 +1,17 @@ +import { fileURLToPath } from 'node:url'; +import { db } from '../apps/api/src/db/client.js'; +import { createImageStore } from '../apps/api/src/features/recipes/imageStore.js'; + +try { + const images = createImageStore( + db, + 'project2', + process.env.UPLOAD_DIR ?? + fileURLToPath(new URL('../uploads/', import.meta.url)), + ); + console.log( + `Removed ${await images.cleanup()} unused images older than 24 hours.`, + ); +} finally { + await db.end(); +} diff --git a/scripts/test-database.ts b/scripts/test-database.ts index 23badab..0f10ccd 100644 --- a/scripts/test-database.ts +++ b/scripts/test-database.ts @@ -118,6 +118,10 @@ await test('recipe model against PostgreSQL', async (t) => { await t.test( 'review migration normalizes existing category labels', async () => { + const legacyImage = '/uploads/11111111-1111-4111-8111-111111111111.jpg'; + await client.query('UPDATE ' + table('recipes') + ' SET image_url=$1', [ + legacyImage, + ]); for (const migration of migrations.slice(3)) await client.query(migration); assert.equal( @@ -125,6 +129,14 @@ await test('recipe model against PostgreSQL', async (t) => { .rows[0].category, 'soup', ); + const metadata = await client.query( + 'SELECT filename,owner_id FROM ' + table('uploaded_images'), + ); + assert.equal( + metadata.rows[0].filename, + legacyImage.slice('/uploads/'.length), + ); + assert.equal(metadata.rows[0].owner_id, authorId); await client.query('DELETE FROM ' + table('recipes')); }, ); diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts index aa5eff0..766e2b7 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -1,6 +1,12 @@ import assert from 'node:assert/strict'; import { randomUUID } from 'node:crypto'; -import { readFile } from 'node:fs/promises'; +import { mkdtemp, readFile, rm, utimes, access } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { + createImageStore, + ImageError, +} from '../apps/api/src/features/recipes/imageStore.js'; import { test } from 'node:test'; import { Pool } from 'pg'; import { print } from 'graphql'; @@ -34,11 +40,13 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { connectionTimeoutMillis: 5000, }); const schema = 'api_test_' + randomUUID().replaceAll('-', ''); + const imageDirectory = await mkdtemp(join(tmpdir(), 'recipe-api-images-')); const api = createApp( createAuthService(createAuthRepository(pool, pool, schema)), false, false, { pool, schema }, + imageDirectory, ); const input: RecipeInput = { title: 'Test soup', @@ -223,6 +231,143 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { owner.cookie, ) ).createRecipe; + await t.test( + 'image ownership, privacy, quotas and orphan cleanup', + async () => { + const png = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aOioAAAAASUVORK5CYII=', + 'base64', + ); + async function upload(cookie?: string) { + return api.fetch('http://localhost/uploads', { + method: 'POST', + body: new Uint8Array(png), + headers: { + 'Content-Type': 'image/png', + 'X-Requested-With': 'recipe-platform', + ...(cookie ? { Cookie: cookie } : {}), + }, + }); + } + assert.equal((await upload()).status, 401); + const uploaded = await upload(owner.cookie); + assert.equal(uploaded.status, 201); + const { imageUrl } = (await uploaded.json()) as { imageUrl: string }; + const image = (cookie?: string) => + api.fetch(`http://localhost${imageUrl}`, { + headers: cookie ? { Cookie: cookie } : {}, + }); + assert.equal((await image()).status, 404); + assert.equal((await image(reader.cookie)).status, 404); + assert.equal((await image(owner.cookie)).status, 200); + await fails( + CreateRecipeDocument, + { input: { ...input, imageUrl } }, + 'BAD_USER_INPUT', + reader.cookie, + ); + await ok( + UpdateRecipeDocument, + { + id: privateRecipe.id, + input: { ...input, visibility: 'private', imageUrl }, + }, + owner.cookie, + ); + assert.equal((await image()).status, 404); + assert.equal((await image(reader.cookie)).status, 404); + assert.equal((await image(owner.cookie)).status, 200); + await ok( + UpdateRecipeDocument, + { + id: privateRecipe.id, + input: { ...input, visibility: 'public', imageUrl }, + }, + owner.cookie, + ); + assert.equal((await image()).status, 200); + assert.equal((await image()).headers.get('cache-control'), 'no-store'); + await ok( + UpdateRecipeDocument, + { + id: privateRecipe.id, + input: { ...input, visibility: 'private', imageUrl }, + }, + owner.cookie, + ); + assert.equal((await image()).status, 404); + const store = createImageStore(pool, schema, imageDirectory); + const filename = imageUrl.slice('/uploads/'.length); + const old = new Date(Date.now() - 25 * 60 * 60 * 1000); + await utimes(join(imageDirectory, filename), old, old); + await pool.query( + `UPDATE "${schema}".uploaded_images SET created_at=$1 WHERE filename=$2`, + [old, filename], + ); + assert.equal(await store.cleanup(), 0); // Referenced private images are retained. + await access(join(imageDirectory, filename)); + await ok( + UpdateRecipeDocument, + { + id: privateRecipe.id, + input: { ...input, title: 'Private soup', visibility: 'private' }, + }, + owner.cookie, + ); + assert.equal(await store.cleanup(), 1); + await assert.rejects(access(join(imageDirectory, filename))); + const restricted = createImageStore(pool, schema, imageDirectory, { + userBytes: 1000, + totalBytes: 2000, + totalFiles: 2, + perHour: 1, + }); + await restricted.upload(owner.user.id, png, 'png'); + await assert.rejects( + restricted.upload(owner.user.id, png, 'png'), + (error: unknown) => + error instanceof ImageError && error.status === 429, + ); + const full = createImageStore(pool, schema, imageDirectory, { + userBytes: 1000, + totalBytes: 1, + totalFiles: 2, + perHour: 20, + }); + await assert.rejects( + full.upload(reader.user.id, png, 'png'), + (error: unknown) => + error instanceof ImageError && error.status === 507, + ); + const userFull = createImageStore(pool, schema, imageDirectory, { + userBytes: 1, + totalBytes: 2000, + totalFiles: 2, + perHour: 20, + }); + await assert.rejects( + userFull.upload(owner.user.id, png, 'png'), + (error: unknown) => + error instanceof ImageError && error.status === 413, + ); + const concurrent = await Promise.allSettled([ + restricted.upload(reader.user.id, png, 'png'), + restricted.upload(reader.user.id, png, 'png'), + ]); + assert.equal( + concurrent.filter((result) => result.status === 'fulfilled').length, + 1, + ); + assert.ok( + concurrent.some( + (result) => + result.status === 'rejected' && + result.reason instanceof ImageError && + result.reason.status === 429, + ), + ); + }, + ); await t.test( 'ratings persist per user, update averages and enforce access', async () => { @@ -633,6 +778,8 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { await pool.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); } finally { await pool.end(); + if (imageDirectory.startsWith(join(tmpdir(), 'recipe-api-images-'))) + await rm(imageDirectory, { recursive: true, force: true }); } } }); diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json index 06da1da..c532c65 100644 --- a/scripts/tsconfig.json +++ b/scripts/tsconfig.json @@ -6,5 +6,5 @@ "types": ["node"], "noEmit": true }, - "include": ["test-recipe-api.ts"] + "include": ["test-recipe-api.ts", "cleanup-images.ts"] } From b7dab40c5ecfefff43e9d9e8281feab0b3cedc31 Mon Sep 17 00:00:00 2001 From: "hasan.fawzi" Date: Tue, 27 Oct 2026 11:14:03 +0100 Subject: [PATCH 4/6] fix(ci): run database and API integration tests with PostgreSQL --- .github/workflows/ci.yml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b8e600..6d183de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,22 @@ on: jobs: quality: runs-on: [self-hosted, linux, x64, t31-project2-ci] + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: t31_ci + POSTGRES_PASSWORD: t31_ci + POSTGRES_DB: t31_ci + ports: + - 5432/tcp + options: >- + --health-cmd "pg_isready -U t31_ci -d t31_ci" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + env: + DATABASE_URL: postgresql://t31_ci:t31_ci@127.0.0.1:${{ job.services.postgres.ports[5432] }}/t31_ci steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -17,6 +33,10 @@ jobs: run: npm run db:check - name: Lint, typecheck, test and build run: npm run check + - name: Test database constraints and migrations + run: npm run test:db + - name: Test recipe API and image storage + run: npm run test:api - run: npx playwright install chromium - run: npm run test:e2e - name: Save tested release From a93eb6fc0464903c9214bb7acd27dce0846cb6c6 Mon Sep 17 00:00:00 2001 From: "hasan.fawzi" Date: Tue, 27 Oct 2026 11:18:18 +0100 Subject: [PATCH 5/6] fix(ci): configure database URL in workflow step --- .github/workflows/ci.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d183de..cac3353 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,10 +20,12 @@ jobs: --health-interval 5s --health-timeout 5s --health-retries 10 - env: - DATABASE_URL: postgresql://t31_ci:t31_ci@127.0.0.1:${{ job.services.postgres.ports[5432] }}/t31_ci steps: - uses: actions/checkout@v4 + - name: Configure test database connection + env: + POSTGRES_PORT: ${{ job.services.postgres.ports[5432] }} + run: echo "DATABASE_URL=postgresql://t31_ci:t31_ci@127.0.0.1:${POSTGRES_PORT}/t31_ci" >> "$GITHUB_ENV" - uses: actions/setup-node@v4 with: { node-version-file: .node-version, cache: npm } - run: npm ci From e54559025d25f6d37bb6b0add93ac162fb36c521 Mon Sep 17 00:00:00 2001 From: "hasan.fawzi" Date: Tue, 27 Oct 2026 11:20:59 +0100 Subject: [PATCH 6/6] fix(ci): use configured test database without Docker --- .github/workflows/ci.yml | 26 ++++++++------------------ docs/recipe-api.md | 7 +++++-- 2 files changed, 13 insertions(+), 20 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cac3353..a415752 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,26 +6,16 @@ on: jobs: quality: runs-on: [self-hosted, linux, x64, t31-project2-ci] - services: - postgres: - image: postgres:16 - env: - POSTGRES_USER: t31_ci - POSTGRES_PASSWORD: t31_ci - POSTGRES_DB: t31_ci - ports: - - 5432/tcp - options: >- - --health-cmd "pg_isready -U t31_ci -d t31_ci" - --health-interval 5s - --health-timeout 5s - --health-retries 10 + env: + DATABASE_URL: ${{ secrets.TEST_DATABASE_URL }} steps: - uses: actions/checkout@v4 - - name: Configure test database connection - env: - POSTGRES_PORT: ${{ job.services.postgres.ports[5432] }} - run: echo "DATABASE_URL=postgresql://t31_ci:t31_ci@127.0.0.1:${POSTGRES_PORT}/t31_ci" >> "$GITHUB_ENV" + - name: Require test database connection + run: | + if [ -z "$DATABASE_URL" ]; then + echo "::error::Set the TEST_DATABASE_URL Actions secret to a dedicated PostgreSQL test database accessible from this runner." + exit 1 + fi - uses: actions/setup-node@v4 with: { node-version-file: .node-version, cache: npm } - run: npm ci diff --git a/docs/recipe-api.md b/docs/recipe-api.md index b55ad25..f798bdd 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -219,8 +219,11 @@ Det bruker ekte register/login og sesjoner, tester public/private, CRUD, save/cookbook og fremprovoserer en barnefeil for å verifisere rollback. Skjemaet slettes i `finally`; eksisterende `project2` og migrasjonshistorikk røres ikke. Krever CREATE SCHEMA-rettighet. Kjør bare mot en database avsatt til utvikling/test. -Integrasjonstestene er egne kommandoer, ikke del av standard CI; runneren må ha -en separat testdatabase og kjøre begge kommandoene for automatisk DB-verifisering. +CI kjører begge integrasjonstestene og nettlesertestene mot `DATABASE_URL` fra +Actions-hemmeligheten `TEST_DATABASE_URL`. Denne må peke til en separat +PostgreSQL-testdatabase som den self-hosted runneren kan nå, med CREATE +SCHEMA-rettighet. CI feiler dersom hemmeligheten mangler. Testdatabasen må +opprettes separat; workflowen krever ikke Docker. Bruk aldri produksjonsdatabasen. Valgfri demoseed, etter migrasjon: