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 cdd21bf..8b81b33 100644 --- a/.env.example +++ b/.env.example @@ -3,3 +3,7 @@ API_HOST=127.0.0.1 API_PORT=3001 # Enable only for the documented local Apache proxy on the VM. 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/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b8e600..a415752 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,8 +6,16 @@ on: jobs: quality: runs-on: [self-hosted, linux, x64, t31-project2-ci] + env: + DATABASE_URL: ${{ secrets.TEST_DATABASE_URL }} steps: - uses: actions/checkout@v4 + - 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 @@ -17,6 +25,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 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/README.md b/README.md index af888c3..6108352 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,15 @@ Prosjekt 2 i **IT2810 Webutvikling** ved NTNU, utviklet av gruppe T31. Recipe Platform er en responsiv oppskriftsapplikasjon hvor brukere kan utforske offentlige oppskrifter, søke, filtrere og sortere resultater, lagre oppskrifter i sin egen kokebok og opprette egne oppskrifter. -Første underveislevering er en fungerende frontend-prototype med statiske mockdata og mockede brukerflyter. Senere leveranser skal koble klienten til en egen GraphQL-backend og database på gruppens virtuelle maskin. +## Status nå + +- Registrering, innlogging og utlogging bruker GraphQL, PostgreSQL og HttpOnly-cookies. +- Explore, My Cookbook og oppskriftsdetaljer henter data fra API-et. +- Oppretting, redigering, sletting, lagring i kokebok og vurderinger lagres i databasen. +- Søk i tittel/beskrivelse, kategori- og tidsfilter samt paginering utføres i backend. Resultatene sorteres med nyeste først. +- Bildeopplasting støtter JPG, PNG og WebP, med tilgangskontroll og opprydding. + +Applikasjonen bruker ikke lenger prototypeoppskriftene som datakilde. Testene bruker egne fixtures. Valgfri seed oppretter to demooppskrifter; et større eksternt datasett er ikke importert. Se [kjente begrensninger](#kjente-begrensninger). ## Lenker @@ -15,7 +23,7 @@ Første underveislevering er en fungerende frontend-prototype med statiske mockd ## Kom i gang -Prosjektet krever Node.js **24.6+** og npm **11+** dersom det kjøres uten Docker. +Uten Docker krever prosjektet Node.js **24.x** og npm **11.x**. `.nvmrc`, `.node-version` og Docker-oppsettet angir den felles referanseversjonen **24.21.0**. ```bash git clone git@git.ntnu.no:IT2810-H26/T31-Project-2.git @@ -112,34 +120,38 @@ 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 +## Autentisering -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. +Registrering, innlogging og utlogging bruker GraphQL og PostgreSQL. Oppretting av bruker og sesjon skjer i én transaksjon, slik at en feil ruller tilbake hele operasjonen. -Session tokens are bearer credentials stored in localStorage to restore login after refresh or reopening the browser. They expire after seven days and are deleted server-side on successful logout. Temporary API or network errors preserve the local token for a later restoration attempt; only a confirmed invalid or expired session clears it. +Sesjoner bruker en HttpOnly-cookie (`t31_project2_session`, SameSite=Lax, Path=/, sju dagers levetid). Sesjonstoken returneres ikke til klientens JavaScript og lagres ikke i localStorage. Utlogging ugyldiggjør sesjonen på serveren. Midlertidige API-feil lar brukeren prøve igjen uten å slette cookien. -Security trade-off: localStorage is readable by JavaScript on the same origin. An XSS vulnerability could steal a token and let an attacker impersonate its owner until expiry or revocation. This prototype accepts that limitation; production deployment should use HTTPS and consider Secure, HttpOnly, SameSite cookies with appropriate CSRF protection. HttpOnly cookies prevent JavaScript from reading the session credential. +Cookie-autentiserte POST-forespørsler krever JSON og `X-Requested-With: recipe-platform`. CORS-tilgang fra andre origins er deaktivert. Sett `AUTH_COOKIE_SECURE=true` når HTTPS er konfigurert. Dagens HTTP-oppsett krever `false`; HTTPS er fortsatt nødvendig for å beskytte passord under transport. -### Protected routes +### Beskyttede ruter -Se [auth-forbedringer](docs/auth-improvements.md) for delt Zod-validering, -feilkoder, genererte klientoperasjoner og rate limiting bak Apache. +`/cookbook`, `/recipes/new` og redigering krever en validert sesjon. Ved oppdatering venter klienten på sesjonsgjenoppretting før eventuell videresending til innlogging. Etter innlogging returneres brukeren til den forespurte ruten. API-et håndhever autentisering, eierskap og synlighet uavhengig av klienten. -`/cookbook` and `/recipes/new` require a validated session. On refresh, the router waits for session restoration before rendering protected content or redirecting to login. A temporary API/network error shows a retry action and preserves the token. Successful login or registration returns to the requested protected URL, including its query and hash. Explore and recipe details remain public. This is client-side routing; future protected API operations must enforce authentication and ownership on the server. +Se [auth-forbedringer](docs/auth-improvements.md) for delt Zod-validering, feilkoder og rate limiting bak Apache. ## Database -Se [databasemodellen](docs/database-model.md) for tabeller, ER-diagram, regler, migrasjon og tester. Modellen utvider autentiseringen og er klar for CRUD i neste steg. +Se [Recipe API og Delivery 2-status](docs/recipe-api.md) for CRUD-kontrakter, +cookie-autentisering, Zod-validering, seed og API-integrasjonstester. + +Se [databasemodellen](docs/database-model.md) for tabeller, ER-diagram, regler, migrasjon og tester. Modellen brukes av autentisering, oppskrifts-CRUD, kokebok og vurderinger. + +Oppsett for CI-testdatabase, migrasjoner og utrulling er samlet i [drift og testing](docs/operations.md). ## Nyttige kommandoer @@ -158,11 +170,10 @@ Se [databasemodellen](docs/database-model.md) for tabeller, ER-diagram, regler, Før en Pull Request bør minst følgende kjøres: ```bash -npm run format -npm run typecheck -npm run lint -npm run test -npm run build +npm run check +npm run test:db +npm run test:api +npm run test:e2e ``` ## Konsept @@ -199,77 +210,26 @@ flowchart TD Cookbook --> Manage["Åpne eller redigere"] ``` -## Første underveislevering - -Første leveranse skal gjøre konseptet forståelig gjennom en sammenhengende prototype. Følgende skal kunne demonstreres med lokale mockdata: - -- Explore med oppskriftskort -- søk, filtrering, sortering og paginering -- Recipe Detail med ingredienser og nummererte steg -- My Cookbook med **All**, **Saved** og **Created by me** -- mock Save to Cookbook -- Add Recipe med validering og repeterbare ingrediens-/instruksjonsfelt -- Login, Register og Sign out med en felles mockbruker i state -- responsive skjermbilder for mobil og desktop -- tydelige tomme tilstander, feil, lasting og bekreftelser - -### Mocking og avgrensninger - -I første leveranse: - -- kommer oppskriftene fra et delt, statisk TypeScript-datasett -- behandles søk, filtrering, sortering og paginering lokalt -- er innlogging og registrering mocket uten ekte passordkontroll -- lagres ikke brukerdata eller nye oppskrifter permanent i databasen -- utføres ingen tester mot en ekstern nettverkstjeneste - -Mockdata ligger adskilt fra komponentene og bruker delte TypeScript-modeller. Dette gjør det mulig å erstatte den lokale datakilden med GraphQL uten å redesigne hele frontendstrukturen. - -## Andre underveislevering - -Etter første underveislevering 2. oktober har vi videreutviklet frontend, -autentisering og databasegrunnlaget. Oversikten beskriver arbeidet som er flettet -inn i `dev` til og med 16. oktober 2026, commit `48e925b`. - -### Utviklet siden første underveislevering - -| Område | Hva som er utviklet | PR | -| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | -| Explore | Responsive filtre og sortering. Søk, filtre og sidetall beholdes i URL-en ved oppdatering og navigering. | [#31](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/31) | -| Add Recipe | Skjema med validering, bildeforhåndsvisning, drag-and-drop og redigerbare ingredienser og instruksjoner. | [#40](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/40) | -| Forbedret opprettingsskjema | Separate ingrediensfelt for navn, mengde og enhet, bildebeskjæring og forbedret omorganisering av ingredienser og steg. | [#52](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/52) | -| My Cookbook | Visninger for lagrede og egne oppskrifter, med søk, filtrering, sortering og paginering. | [#43](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/43) | -| Oppskriftsdetaljer | Detaljside med bilde, forfatter, tilberedningsinformasjon, ingredienser og instruksjoner. Justerbare porsjoner med skalering av mengder, lagrings- og vurderingsinteraksjoner og tilbakegang til tidligere søk og filtre. | [#46](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/46) | -| Navigasjon | Refaktorert header med felles logo- og lenkekomponenter og tilpasning til ulike skjermstørrelser. | [#45](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/45) | -| Autentisering | Registrering, innlogging, utlogging og vedvarende sesjoner med PostgreSQL og passordhashing. Beskyttede ruter venter på sesjonsgjenoppretting før eventuell videresending til login. | [#41](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/41) | -| Auth-forbedringer | Delte Zod-skjemaer, validering av sesjons-ID, strukturerte feilkoder, genererte GraphQL-operasjoner og enkel rate limiting for login og registrering. | [#53](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/53) | -| Databasemodell | Relasjoner for oppskrifter, forfattere, ingredienser, instruksjoner, tagger, bokmerker og vurderinger. Migrasjoner, indekser og datavalidering, valgfritt cuisine-felt, faste kategorier og kildehenvisning for oppskriftskopier. | [#47](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/47) | - -I tillegg er følgende gjennomført: +## Leveransehistorikk -- **Feilhåndtering:** Egen 404-side og separat håndtering av ukjente oppskrifts-ID-er. -- **Lokalt utviklingsmiljø:** Docker-oppsett for frontend, API og PostgreSQL, med - oppdatert dokumentasjon for installasjon og oppstart. -- **Testing og dokumentasjon:** Utvidede frontend-, backend-, database- og - nettlesertester. Dokumentasjon av databasemodellen, autentisering og videre - serverintegrasjon. +Beskrivelsene av første og andre underveislevering er samlet i [leveransehistorikken](docs/delivery-history.md). -## Planlagt arkitektur +## Arkitektur ```mermaid flowchart TD UI["React-grensesnitt"] --> State["Klientstate"] State --> Mock["Mockdata - Delivery 1"] - State --> Client["GraphQL-klient - senere"] + State --> Client["Typet GraphQL-klient"] Client --> API["Node og TypeScript GraphQL API"] API --> DB["Database på NTNU VM"] ``` -Søk, filtrering og sortering holdes adskilt fra presentasjonskomponentene. I senere leveranser skal operasjonene utføres på hele datasettet i backend/databasen, ikke bare på oppskriftene som tilfeldigvis er lastet i nettleseren. +Søk, filtrering og sortering holdes adskilt fra presentasjonskomponentene. Søk, filtrering og nyeste-først-sortering utføres i databasen før paginering. Se [arkitektur og prosjektstruktur](docs/architecture.md) for ansvarsfordeling og tekniske valg. ### Domenemodeller -Den delte datamodellen planlegges rundt: +Datamodellen omfatter: - `Recipe`: tittel, beskrivelse, forfatter, synlighet, bilde, tid, porsjoner, kategorier, ingredienser, steg og vurdering - `Ingredient`: navn, mengde, enhet og valgfri merknad @@ -290,9 +250,9 @@ Den delte datamodellen planlegges rundt: - plain CSS med designvariabler og responsive layouts - Vitest og Testing Library - ESLint og Prettier -- Playwright for planlagte ende-til-ende-tester +- Playwright for ende-til-ende-tester -Frontend ligger under `apps/web`, backend under `apps/api`, og delte kontrakter ligger under `contracts`. +Se [arkitektur og prosjektstruktur](docs/architecture.md) for mapper, genererte typer og valget av SQL sammen med Drizzle. ## Tilgjengelighet @@ -314,7 +274,7 @@ Applikasjonen skal fungere på både mobil og desktop. Oppskriftsgridet går fra Vi arbeider for en mer bærekraftig løsning gjennom: - paginering eller dynamisk lasting i stedet for å sende hele datasettet til klienten -- serverbasert søk, filtrering og sortering i senere leveranser +- serverbasert søk, filtrering og nyeste-først-sortering - optimaliserte bilder i passende størrelser - gjenbrukbare komponenter og begrenset unødvendig JavaScript - færre unødvendige nettverkskall @@ -322,9 +282,9 @@ Vi arbeider for en mer bærekraftig løsning gjennom: ## Testing og kvalitetssikring -Testene skal være deterministiske og uten avhengighet til levende nettverkstjenester. Første leveranse prioriterer tester av faktisk brukerinteraksjon: +Enhetstestene bruker kontrollerte testdata. Database- og API-integrasjonstestene bruker PostgreSQL i isolerte skjemaer. CI kjører også Playwright med en separat testdatabase. Se [drift og testing](docs/operations.md). Testene dekker blant annet: -- validering og mocksession for Login/Register +- validering, cookie-sesjoner og tilgangskontroll for Login/Register - handlinger i RecipeCard - filtrering og paginering - validering i Add Recipe @@ -388,8 +348,7 @@ Velg eller opprett et issue før arbeidet starter. PR-en skal oppsummere endring ## Sikkerhet - Ikke commit `.env`, tokens, API-nøkler, databasepassord eller ekte brukeropplysninger. -- Mockautentisering skal aldri behandle eller lagre ekte passord. -- Valider brukerinput både i klienten og senere i backend. +- Valider brukerinput både i klienten og i backend. - Bruk parametriserte databasespørringer eller et sikkert datalag. - Håndhev eierskap og synlighet i backend, ikke bare ved å skjule knapper i frontend. - Eksponer ikke detaljerte interne feilmeldinger til sluttbrukeren. @@ -414,13 +373,15 @@ Generert kode og dokumentasjon blir kontrollert gjennom kodegjennomgang og manue KI-verktøy får ikke ekte passord, tokens, personopplysninger eller andre hemmeligheter. -## Kjente begrensninger i første leveranse +## Kjente begrensninger -- Autentisering og session er kun mocket. -- Oppskrifter og brukere kommer fra statiske TypeScript-data. -- Endringer overlever ikke nødvendigvis en sideoppdatering. -- GraphQL, database og persistent lagring kobles til i senere leveranser. -- Enkelte planlagte sider eller interaksjoner kan fortsatt være under arbeid. +- Søk dekker tittel og beskrivelse; ingrediens- og tagsøk er videre arbeid. +- Bare nyeste-først-sortering er implementert. Trending og øvrige sorteringer er ikke tilgjengelige. +- Utkast beholdes bare i skjemaet og overlever ikke navigering eller oppdatering. +- Seed inneholder to demooppskrifter og demonstrerer ikke ytelse med store datamengder. +- Bildeoperasjoner bruker en global lås for korrekt koordinering. Dette begrenser samtidige skriveoperasjoner. +- Bildekvoter har faste grenser. Registrering har IP-begrensning, men flere kontoer kan fortsatt omgå brukerkvotene. Refererte bilder teller mot totalgrensen og slettes ikke av cleanup. +- VM-en bruker foreløpig HTTP. HTTPS er nødvendig for å beskytte innlogging under transport. ## Gruppe og samarbeid 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 d3c982a..26232d3 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -1,3 +1,10 @@ +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'; import { readFileSync } from 'node:fs'; import { createSchema, createYoga } from 'graphql-yoga'; @@ -9,16 +16,101 @@ import { } from './features/auth/authResolvers.js'; import { authClientKey } from './features/auth/authRateLimit.js'; import { authService, type AuthService } from './features/auth/authService.js'; +import { + readSessionCookie, + sessionCookie, + SESSION_COOKIE, +} from './features/auth/sessionCookie.js'; export function createApp( service: AuthService = authService, 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 images = createImageStore( + database.pool ?? db, + database.schema ?? 'project2', + uploadDirectory, + ); const authResolvers = createAuthResolvers(service); + const recipes = createRecipeResolvers( + createRecipeRepository(database.pool ?? db, database.schema ?? 'project2'), + ); + const cookies = new WeakMap(); return createYoga<{ req?: IncomingMessage }, AuthContext>({ - context: ({ request, req }) => ({ - authClient: authClientKey(request, req?.socket.remoteAddress, trustProxy), - }), + cors: false, + graphiql: { + defaultHeaders: JSON.stringify({ 'X-Requested-With': 'recipe-platform' }), + }, + plugins: [ + { + async onRequest({ request, fetchAPI, endResponse }) { + const imageResponse = await handleImageRequest( + request, + service, + images, + ); + if (imageResponse) { + endResponse(imageResponse); + return; + } + if ( + request.method === 'POST' && + (request.headers.get('x-requested-with') !== 'recipe-platform' || + request.headers.get('content-type')?.split(';')[0]?.trim() !== + 'application/json') + ) { + endResponse( + new fetchAPI.Response( + JSON.stringify({ + errors: [ + { + message: 'Request blocked.', + extensions: { code: 'FORBIDDEN' }, + }, + ], + }), + { + status: 403, + headers: { 'Content-Type': 'application/json' }, + }, + ), + ); + } + }, + onResponse({ request, response }) { + const cookie = cookies.get(request); + if (cookie) response.headers.append('Set-Cookie', cookie); + response.headers.set('Cache-Control', 'no-store'); + }, + }, + ], + context: async ({ request, req }) => { + const token = readSessionCookie(request); + const user = token ? await service.currentUser(token) : null; + if ( + !user && + request.headers.get('cookie')?.includes(SESSION_COOKIE + '=') + ) + cookies.set(request, sessionCookie(null, secureCookie)); + const context: AuthContext = { + authClient: authClientKey( + request, + req?.socket.remoteAddress, + trustProxy, + ), + user, + sessionToken: user ? token : null, + setSession: (nextToken) => { + cookies.set(request, sessionCookie(nextToken, secureCookie)); + context.sessionToken = nextToken; + }, + }; + return context; + }, schema: createSchema({ typeDefs: readFileSync( new URL('./schema.graphql', import.meta.url), @@ -28,9 +120,11 @@ export function createApp( Query: { health: () => 'ok', ...authResolvers.Query, + ...recipes.Query, }, Mutation: { ...authResolvers.Mutation, + ...recipes.Mutation, }, } satisfies Resolvers, }), 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/db/seed.ts b/apps/api/src/db/seed.ts new file mode 100644 index 0000000..3c58e23 --- /dev/null +++ b/apps/api/src/db/seed.ts @@ -0,0 +1,10 @@ +import { db } from './client.js'; +import { seedDatabase } from './seedData.js'; +try { + await seedDatabase(db, process.env.SEED_PASSWORD); + console.log( + 'Demo data ready. Existing seed rows and passwords were not overwritten.', + ); +} finally { + await db.end(); +} diff --git a/apps/api/src/db/seedData.ts b/apps/api/src/db/seedData.ts new file mode 100644 index 0000000..42554bd --- /dev/null +++ b/apps/api/src/db/seedData.ts @@ -0,0 +1,61 @@ +import { hash } from 'argon2'; +import type { Pool } from 'pg'; + +// Explicit opt-in demo data; never run automatically during deploy. +const authorId = '11111111-1111-4111-8111-111111111111'; +export async function seedDatabase( + pool: Pool, + password: string | undefined, + schema = 'project2', +) { + if (!/^[a-z_][a-z0-9_]*$/.test(schema)) + throw new Error('Invalid database schema.'); + if (!password || password.length < 12) { + throw new Error( + 'Set SEED_PASSWORD (at least 12 characters) before running db:seed.', + ); + } + const passwordHash = await hash(password); + const client = await pool.connect(); + try { + await client.query('BEGIN'); + await client.query( + `INSERT INTO ${schema}.users (id,name,email,password_hash) + VALUES ($1,'Demo Cook','demo@example.invalid',$2) ON CONFLICT (id) DO NOTHING`, + [authorId, passwordHash], + ); + for (const [id, title, visibility] of [ + ['22222222-2222-4222-8222-222222222222', 'Demo vegetable soup', 'public'], + ['33333333-3333-4333-8333-333333333333', 'Demo private soup', 'private'], + ]) { + const inserted = await client.query( + `INSERT INTO ${schema}.recipes + (id,author_id,title,description,category,difficulty,visibility,prep_minutes,cook_minutes,servings) + VALUES ($1,$2,$3,'Simple demonstration recipe','soup','easy',$4,5,15,2) + ON CONFLICT (id) DO NOTHING RETURNING id`, + [id, authorId, title, visibility], + ); + if (!inserted.rowCount) continue; + await client.query( + `INSERT INTO ${schema}.recipe_ingredients (recipe_id,name,amount,unit,position) + VALUES ($1,'Water',500,'ml',1),($1,'Carrots',2,'',2)`, + [id], + ); + await client.query( + `INSERT INTO ${schema}.recipe_instructions (recipe_id,text,position) + VALUES ($1,'Chop the carrots.',1),($1,'Simmer in water until tender.',2)`, + [id], + ); + await client.query( + `INSERT INTO ${schema}.recipe_tags (recipe_id,tag) VALUES ($1,'demo')`, + [id], + ); + } + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } finally { + client.release(); + } +} diff --git a/apps/api/src/features/auth/authApp.test.ts b/apps/api/src/features/auth/authApp.test.ts index a674c71..e83ddce 100644 --- a/apps/api/src/features/auth/authApp.test.ts +++ b/apps/api/src/features/auth/authApp.test.ts @@ -1,6 +1,6 @@ // @vitest-environment node import { describe, expect, it, vi } from 'vitest'; -import { print } from 'graphql'; +import { print, parse } from 'graphql'; import { createApp } from '../../app.js'; import { createAuthService } from './authService.js'; import type { AuthRepository } from './authRepository.js'; @@ -10,19 +10,22 @@ import { SignOutDocument, RegisterDocument, } from '../../../../../contracts/generated.js'; - const token = '11111111-1111-4111-8111-111111111111'; const user = { id: '22222222-2222-4222-8222-222222222222', name: 'Hasan', email: 'hasan@example.com', }; -function setup() { +function setup(secure = false) { let active = false; + let cookie = ''; const repository: AuthRepository = { findUserByEmail: vi.fn(async () => ({ ...user, passwordHash: 'hash' })), createUser: vi.fn(async () => user), - createUserWithSession: vi.fn(async () => ({ user, sessionToken: token })), + createUserWithSession: vi.fn(async () => { + active = true; + return { user, sessionToken: token }; + }), createSession: vi.fn(async () => { active = true; return token; @@ -32,65 +35,159 @@ function setup() { active = false; }), }; - const service = createAuthService(repository, { - hash: async () => 'hash', - verify: async (_hash, password) => password === 'x', - }); - const app = createApp(service, false); + const app = createApp( + createAuthService(repository, { + hash: async () => 'hash', + verify: async (_hash, password) => password === 'x', + }), + false, + secure, + ); async function request( document: Parameters[0], - variables: Record, + variables: Record = {}, + sentCookie = cookie, + csrf = true, ) { const response = await app.fetch('http://localhost/graphql', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { + 'Content-Type': 'application/json', + ...(csrf ? { 'X-Requested-With': 'recipe-platform' } : {}), + ...(sentCookie ? { Cookie: sentCookie } : {}), + }, body: JSON.stringify({ query: print(document), variables }), }); - return (await response.json()) as { + const setCookie = response.headers.get('set-cookie'); + if (setCookie) cookie = setCookie.split(';')[0]!; + const result = (await response.json()) as { data: { - login?: { sessionToken: string }; + login?: { user: typeof user }; + register?: { user: typeof user }; currentUser?: typeof user | null; signOut?: boolean; }; errors?: { extensions: { code: string } }[]; }; + return { ...result, cookie: setCookie, status: response.status }; } - return { repository, request }; + return { + repository, + request, + expire: () => { + active = false; + }, + }; } -describe('GraphQL authentication contract', () => { - it('logs in with a short existing password, restores session and invalidates it on logout', async () => { +describe('cookie GraphQL authentication', () => { + it('sets an HttpOnly cookie, restores from context and revokes the session on logout', async () => { const { request } = setup(); const login = await request(LoginDocument, { email: user.email, password: 'x', }); expect(login.errors).toBeUndefined(); - expect(login.data.login?.sessionToken).toBe(token); - expect( - (await request(CurrentUserDocument, { sessionToken: token })).data - .currentUser, - ).toEqual(user); + expect(login.data.login).toEqual({ user }); + expect(JSON.stringify(login.data)).not.toContain(token); + expect(login.cookie).toContain('HttpOnly'); + expect(login.cookie).toContain('SameSite=Lax'); + expect(login.cookie).toContain('Path=/'); + expect(login.cookie).toContain('Max-Age=604800'); + expect(login.cookie).not.toContain('Secure'); + expect(login.cookie).not.toContain('Domain='); + expect((await request(CurrentUserDocument)).data.currentUser).toEqual(user); + const logout = await request(SignOutDocument); + expect(logout.data.signOut).toBe(true); + expect(logout.cookie).toContain('Max-Age=0'); + expect(logout.cookie).toContain('Path=/'); expect( - (await request(SignOutDocument, { sessionToken: token })).data.signOut, - ).toBe(true); - expect( - (await request(CurrentUserDocument, { sessionToken: token })).data - .currentUser, + (await request(CurrentUserDocument, {}, 't31_project2_session=' + token)) + .data.currentUser, ).toBeNull(); }); - it('does not query the repository for malformed session IDs', async () => { + it('registration also creates a cookie without exposing the token', async () => { const { request, repository } = setup(); + vi.mocked(repository.findUserByEmail).mockResolvedValueOnce(null); + const registered = await request(RegisterDocument, { + name: user.name, + email: user.email, + password: 'secret', + }); + expect(registered.errors).toBeUndefined(); + expect(registered.data.register).toEqual({ user }); + expect(registered.cookie).toContain('HttpOnly'); + expect((await request(CurrentUserDocument)).data.currentUser).toEqual(user); + }); + it('sets Secure when explicitly enabled for HTTPS', async () => { + const { request } = setup(true); expect( - (await request(CurrentUserDocument, { sessionToken: 'broken' })).data - .currentUser, - ).toBeNull(); - expect( - (await request(SignOutDocument, { sessionToken: 'broken' })).data.signOut, - ).toBe(false); + (await request(LoginDocument, { email: user.email, password: 'x' })) + .cookie, + ).toContain('; Secure'); + expect((await request(SignOutDocument)).cookie).toContain('; Secure'); + }); + it('treats absent, malformed and expired cookies as anonymous', async () => { + const { request, repository, expire } = setup(); + expect((await request(CurrentUserDocument)).data.currentUser).toBeNull(); + const malformed = await request( + CurrentUserDocument, + {}, + 't31_project2_session=broken', + ); + expect(malformed.data.currentUser).toBeNull(); + expect(malformed.cookie).toContain('Max-Age=0'); expect(repository.findUserBySession).not.toHaveBeenCalled(); - expect(repository.deleteSession).not.toHaveBeenCalled(); + await request(LoginDocument, { email: user.email, password: 'x' }); + expire(); + const expired = await request(CurrentUserDocument); + expect(expired.data.currentUser).toBeNull(); + expect(expired.cookie).toContain('Max-Age=0'); + }); + it('does not clear the cookie or claim success when session revocation fails', async () => { + const { request, repository } = setup(); + await request(LoginDocument, { email: user.email, password: 'x' }); + vi.mocked(repository.deleteSession).mockRejectedValueOnce( + new Error('Database offline'), + ); + const logout = await request(SignOutDocument); + expect(logout.errors).toBeDefined(); + expect(logout.cookie).toBeNull(); + expect((await request(CurrentUserDocument)).data.currentUser).toEqual(user); + }); + it('rejects browser-simple POSTs before executing authentication', async () => { + const { request, repository } = setup(); + expect( + ( + await request( + LoginDocument, + { email: user.email, password: 'x' }, + '', + false, + ) + ).status, + ).toBe(403); + expect(repository.findUserByEmail).not.toHaveBeenCalled(); + }); + it('rejects the old token-bearing GraphQL contract', async () => { + const { request } = setup(); + expect( + ( + await request( + parse('query { currentUser(sessionToken: "old") { id } }'), + ) + ).errors, + ).toBeDefined(); + expect( + ( + await request( + parse( + 'mutation { login(email:"a@example.com",password:"x") { sessionToken } }', + ), + ) + ).errors, + ).toBeDefined(); }); - it('returns structured codes for invalid input, credentials, duplicate email and rate limits', async () => { + it('preserves structured errors and rate limiting', async () => { const { request } = setup(); expect( (await request(LoginDocument, { email: 'a@', password: 'x' })).errors?.[0] @@ -103,7 +200,7 @@ describe('GraphQL authentication contract', () => { expect( ( await request(RegisterDocument, { - name: 'Hasan', + name: user.name, email: user.email, password: 'secret', }) diff --git a/apps/api/src/features/auth/authRepository.ts b/apps/api/src/features/auth/authRepository.ts index 61f1327..18fe834 100644 --- a/apps/api/src/features/auth/authRepository.ts +++ b/apps/api/src/features/auth/authRepository.ts @@ -56,13 +56,16 @@ export interface AuthRepository { export function createAuthRepository( pool: Pool = db, executor: Pick = pool, + schema = 'project2', ): AuthRepository { + if (!/^[a-z_][a-z0-9_]*$/.test(schema)) + throw new Error('Invalid database schema.'); return { async findUserByEmail(email) { const result = await executor.query( ` SELECT id, name, email, password_hash - FROM project2.users + FROM ${schema}.users WHERE email = $1 LIMIT 1 `, @@ -86,7 +89,7 @@ export function createAuthRepository( async createUser(name, email, passwordHash) { const result = await executor.query( ` - INSERT INTO project2.users (name, email, password_hash) + INSERT INTO ${schema}.users (name, email, password_hash) VALUES ($1, $2, $3) RETURNING id, name, email `, @@ -106,7 +109,7 @@ export function createAuthRepository( const client = await pool.connect(); try { await client.query('BEGIN'); - const repository = createAuthRepository(pool, client); + const repository = createAuthRepository(pool, client, schema); const user = await repository.createUser(name, email, passwordHash); const sessionToken = await repository.createSession(user.id, expiresAt); await client.query('COMMIT'); @@ -134,7 +137,7 @@ export function createAuthRepository( async createSession(userId, expiresAt) { const result = await executor.query<{ id: string }>( ` - INSERT INTO project2.sessions (user_id, expires_at) + INSERT INTO ${schema}.sessions (user_id, expires_at) VALUES ($1, $2) RETURNING id `, @@ -155,8 +158,8 @@ export function createAuthRepository( const result = await executor.query( ` SELECT users.id, users.name, users.email - FROM project2.sessions AS sessions - JOIN project2.users AS users + FROM ${schema}.sessions AS sessions + JOIN ${schema}.users AS users ON users.id = sessions.user_id WHERE sessions.id = $1 AND sessions.expires_at > now() @@ -172,7 +175,7 @@ export function createAuthRepository( if (!sessionTokenSchema.safeParse(sessionToken).success) return; await executor.query( ` - DELETE FROM project2.sessions + DELETE FROM ${schema}.sessions WHERE id = $1 `, [sessionToken], diff --git a/apps/api/src/features/auth/authResolvers.ts b/apps/api/src/features/auth/authResolvers.ts index 1c57c90..b973c66 100644 --- a/apps/api/src/features/auth/authResolvers.ts +++ b/apps/api/src/features/auth/authResolvers.ts @@ -1,8 +1,12 @@ import { authService, type AuthService } from './authService.js'; import { createAuthRateLimiter } from './authRateLimit.js'; +import type { PublicUser } from './authRepository.js'; export interface AuthContext { authClient: string; + user: PublicUser | null; + sessionToken: string | null; + setSession: (token: string | null) => void; } export function createAuthResolvers( @@ -11,8 +15,8 @@ export function createAuthResolvers( ) { return { Query: { - currentUser: (_parent: unknown, args: { sessionToken: string }) => - service.currentUser(args.sessionToken), + currentUser: (_parent: unknown, _args: unknown, context: AuthContext) => + context.user, }, Mutation: { @@ -26,7 +30,13 @@ export function createAuthResolvers( context: AuthContext, ) => { limiter.check('register', context.authClient); - return service.register(args.name, args.email, args.password); + return service + .register(args.name, args.email, args.password) + .then((result) => { + context.setSession(result.sessionToken); + context.user = result.user; + return { user: result.user }; + }); }, login: ( @@ -38,11 +48,23 @@ export function createAuthResolvers( context: AuthContext, ) => { limiter.check('login', context.authClient); - return service.login(args.email, args.password); + return service.login(args.email, args.password).then((result) => { + context.setSession(result.sessionToken); + context.user = result.user; + return { user: result.user }; + }); }, - signOut: (_parent: unknown, args: { sessionToken: string }) => - service.signOut(args.sessionToken), + signOut: async ( + _parent: unknown, + _args: unknown, + context: AuthContext, + ) => { + await service.signOut(context.sessionToken ?? ''); + context.setSession(null); + context.user = null; + return true; + }, }, }; } diff --git a/apps/api/src/features/auth/sessionCookie.ts b/apps/api/src/features/auth/sessionCookie.ts new file mode 100644 index 0000000..d0db972 --- /dev/null +++ b/apps/api/src/features/auth/sessionCookie.ts @@ -0,0 +1,16 @@ +import { sessionTokenSchema } from '@t31/validation'; + +export const SESSION_COOKIE = 't31_project2_session'; +export function readSessionCookie(request: Request): string | null { + const values = (request.headers.get('cookie') ?? '') + .split(';') + .map((value) => value.trim()) + .filter((value) => value.startsWith(SESSION_COOKIE + '=')); + if (values.length !== 1) return null; + const token = values[0]!.slice(SESSION_COOKIE.length + 1); + return sessionTokenSchema.safeParse(token).success ? token : null; +} +export function sessionCookie(token: string | null, secure: boolean) { + // Host-only cookie: works through local Vite and the VM's /project2/api proxy. + return `${SESSION_COOKIE}=${token ?? ''}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${token ? 604800 : 0}${secure ? '; Secure' : ''}`; +} 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 new file mode 100644 index 0000000..e91a3e0 --- /dev/null +++ b/apps/api/src/features/recipes/imageStorage.test.ts @@ -0,0 +1,73 @@ +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' }; +const service: AuthService = { + currentUser: async (value) => (value === token ? user : null), + login: async () => ({ user, sessionToken: token }), + register: async () => ({ user, sessionToken: token }), + signOut: async () => true, +}; +const png = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aOioAAAAASUVORK5CYII=', + 'base64', +); +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('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 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(store.upload).not.toHaveBeenCalled(); + }); + 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 new file mode 100644 index 0000000..e26be81 --- /dev/null +++ b/apps/api/src/features/recipes/imageStorage.ts @@ -0,0 +1,105 @@ +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 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, 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, + 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 (!imageFilenamePattern.test(filename)) + return failure(404, 'Image not found.'); + try { + 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) { + 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); + 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.'); + 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.'); + 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/recipeContract.test.ts b/apps/api/src/features/recipes/recipeContract.test.ts new file mode 100644 index 0000000..6d172f0 --- /dev/null +++ b/apps/api/src/features/recipes/recipeContract.test.ts @@ -0,0 +1,74 @@ +import { readFileSync } from 'node:fs'; +import { buildSchema, graphql, isEnumType, parse, validate } from 'graphql'; +import { describe, expect, it } from 'vitest'; +import { categorySchema, recipeInputSchema } from './recipeValidation.js'; + +const schema = buildSchema( + readFileSync(new URL('../../schema.graphql', import.meta.url), 'utf8'), +); + +describe('recipe GraphQL contract', () => { + it('keeps enum values consistent with input validation', () => { + const values = (name: string) => { + const type = schema.getType(name); + if (!isEnumType(type)) throw new Error(`${name} must be an enum`); + return type.getValues().map((value) => value.name); + }; + expect(values('RecipeCategory')).toEqual(categorySchema.options); + expect(values('RecipeDifficulty')).toEqual( + recipeInputSchema.shape.difficulty.options, + ); + expect(values('RecipeVisibility')).toEqual( + recipeInputSchema.shape.visibility.options, + ); + expect(values('CookbookScope')).toEqual(['all', 'saved', 'created']); + }); + + it('accepts all shared operations against the schema', () => { + const operations = readFileSync( + new URL('../../../../../contracts/operations.graphql', import.meta.url), + 'utf8', + ); + expect(validate(schema, parse(operations))).toEqual([]); + }); + + it.each([ + ['RecipeCategory', 'Soup'], + ['RecipeDifficulty', 'expert'], + ['RecipeVisibility', 'hidden'], + ['CookbookScope', 'everyone'], + ])('rejects invalid %s variables before resolving', async (type, value) => { + const field = type === 'CookbookScope' ? 'cookbook' : 'recipes'; + const argument = + type === 'CookbookScope' + ? 'scope: $value' + : type === 'RecipeCategory' + ? 'input: { category: $value }' + : ''; + // Difficulty/visibility are mutation inputs; use their real input fields. + const source = argument + ? `query($value: ${type}) { ${field}(${argument}) { totalCount } }` + : `mutation($value: ${type}!) { + createRecipe(input: { + title: "Soup", description: "", category: soup, + difficulty: ${type === 'RecipeDifficulty' ? '$value' : 'easy'}, + visibility: ${type === 'RecipeVisibility' ? '$value' : 'public'}, + prepMinutes: 0, cookMinutes: 10, servings: 1, + ingredients: [], instructions: [], tags: [] + }) { id } + }`; + let resolved = false; + const result = await graphql({ + schema, + source, + variableValues: { value }, + rootValue: { + [argument ? field : 'createRecipe']: () => { + resolved = true; + }, + }, + }); + expect(result.errors?.[0]?.message).toContain('does not exist'); + expect(resolved).toBe(false); + }); +}); diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts new file mode 100644 index 0000000..98e7505 --- /dev/null +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -0,0 +1,268 @@ +import { GraphQLError } from 'graphql'; +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)) + throw new Error('Invalid database schema.'); + const t = (name: string) => `"${schema}"."${name}"`; + const ownedByViewer = 'r.author_id=$1::uuid'; + const publicRecipe = "r.visibility='public'"; + const visibleToViewer = `(${publicRecipe} OR ${ownedByViewer})`; + const savedByViewer = `EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)`; + + function listAccessCondition(scope: 'explore' | CookbookScope) { + if (scope === 'explore') return publicRecipe; + const membership: Record = { + created: ownedByViewer, + saved: savedByViewer, + all: `(${ownedByViewer} OR ${savedByViewer})`, + }; + return `${visibleToViewer} AND (${membership[scope]})`; + } + + function listFilterConditions() { + // Keep filter parameters separate from access rules; shared by count and rows. + return [ + "($2='' OR strpos(lower(r.title || ' ' || r.description),lower($2))>0)", + '($3::text IS NULL OR r.category=$3)', + '($4::int IS NULL OR r.prep_minutes+r.cook_minutes <= $4)', + ]; + } + // One read includes ordered children and derived values; no per-recipe queries. + const select = `SELECT r.id, r.title, r.description, r.category, r.cuisine, + r.difficulty, r.visibility, r.image_url AS "imageUrl", r.source_recipe_id AS "sourceRecipeId", + r.prep_minutes AS "prepMinutes", r.cook_minutes AS "cookMinutes", r.servings, + to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "createdAt", + to_char(r.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "updatedAt", + json_build_object('id',u.id,'name',u.name) AS author, + coalesce(r.author_id = $1::uuid,false) AS "isCreatedByCurrentUser", + 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 + FROM ${t('recipes')} r JOIN ${t('users')} u ON u.id=r.author_id`; + + async function transaction(work: (client: PoolClient) => Promise) { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + const result = await work(client); + await client.query('COMMIT'); + return result; + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } finally { + client.release(); + } + } + async function read( + executor: Pick, + id: string, + userId: string | null, + ) { + const result = await executor.query( + select + ` WHERE r.id=$2 AND ${visibleToViewer}`, + [userId, id], + ); + return result.rows[0] ?? null; + } + async function readRequired(client: PoolClient, id: string, userId: string) { + const recipe = await read(client, id, userId); + if (!recipe) throw new Error('Recipe could not be read after writing.'); + return recipe; + } + async function owned(client: PoolClient, id: string, userId: string) { + const result = await client.query( + `SELECT id FROM ${t('recipes')} WHERE id=$1 AND author_id=$2 FOR UPDATE`, + [id, userId], + ); + if (!result.rowCount) + throw new GraphQLError('Recipe not found or not owned by you.', { + extensions: { code: 'NOT_FOUND' }, + }); + } + async function children(client: PoolClient, id: string, input: RecipeInput) { + for (const [index, ingredient] of input.ingredients.entries()) { + await client.query( + `INSERT INTO ${t('recipe_ingredients')} (recipe_id,name,amount,unit,note,position) VALUES ($1,$2,$3,$4,$5,$6)`, + [ + id, + ingredient.name, + ingredient.amount, + ingredient.unit, + ingredient.note, + index + 1, + ], + ); + } + for (const [index, instruction] of input.instructions.entries()) + await client.query( + `INSERT INTO ${t('recipe_instructions')} (recipe_id,text,position) VALUES ($1,$2,$3)`, + [id, instruction, index + 1], + ); + for (const tag of input.tags) + await client.query( + `INSERT INTO ${t('recipe_tags')} (recipe_id,tag) VALUES ($1,$2)`, + [id, tag], + ); + } + const values = (input: RecipeInput) => [ + input.title, + input.description, + input.imageUrl, + input.category, + input.cuisine, + input.difficulty, + input.visibility, + input.prepMinutes, + input.cookMinutes, + input.servings, + ]; + return { + get: (id: string, userId: string | null) => read(pool, id, userId), + async list( + input: ListInput, + userId: string | null, + scope: 'explore' | CookbookScope = 'explore', + ) { + const where = ` WHERE ${[listAccessCondition(scope), ...listFilterConditions()].join(' AND ')}`; + const args = [ + userId, + input.search, + input.category ?? null, + input.maxCookingMinutes ?? null, + ]; + // Count and rows share a snapshot, including when another request creates/deletes recipes. + return transaction(async (client) => { + await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ'); + const count = await client.query<{ total: number }>( + `SELECT count(*)::int AS total, $1::uuid AS "viewerId" FROM ${t('recipes')} r` + + where, + args, + ); + const totalCount = count.rows[0]!.total; + const totalPages = Math.ceil(totalCount / input.pageSize); + const page = Math.min(input.page, Math.max(totalPages, 1)); + const rows = await client.query( + select + + where + + ' ORDER BY r.created_at DESC,r.id DESC LIMIT $5 OFFSET $6', + [...args, input.pageSize, (page - 1) * input.pageSize], + ); + return { + items: rows.rows, + totalCount, + totalPages, + page, + pageSize: input.pageSize, + }; + }); + }, + 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], + ); + const id = result.rows[0]!.id; + await children(client, id, input); + return readRequired(client, id, userId); + }); + }, + 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], + ); + for (const name of [ + 'recipe_ingredients', + 'recipe_instructions', + 'recipe_tags', + ]) + await client.query(`DELETE FROM ${t(name)} WHERE recipe_id=$1`, [id]); + await children(client, id, input); + return readRequired(client, id, userId); + }); + }, + 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; + }); + }, + async save(id: string, 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 saved.', + { extensions: { code: 'FORBIDDEN' } }, + ); + await client.query( + `INSERT INTO ${t('saved_recipes')} (user_id,recipe_id) VALUES ($1,$2) ON CONFLICT DO NOTHING`, + [userId, id], + ); + return readRequired(client, id, userId); + }); + }, + async unsave(id: string, userId: string) { + await pool.query( + `DELETE FROM ${t('saved_recipes')} WHERE user_id=$1 AND recipe_id=$2`, + [userId, id], + ); + 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 new file mode 100644 index 0000000..044fcc1 --- /dev/null +++ b/apps/api/src/features/recipes/recipeResolvers.ts @@ -0,0 +1,71 @@ +import { GraphQLError } from 'graphql'; +import { z } from 'zod'; +import type { AuthContext as ApiContext } from '../auth/authResolvers.js'; +import type { Resolvers } from '../../generated.js'; +import type { RecipeRepository } from './recipeRepository.js'; +import { + listInputSchema, + recipeId, + recipeInputSchema, + validate, +} from './recipeValidation.js'; + +function requireUser(context: ApiContext) { + if (!context.user) + throw new GraphQLError('Please log in.', { + extensions: { code: 'UNAUTHENTICATED' }, + }); + return context.user.id; +} +export function createRecipeResolvers(repository: RecipeRepository) { + return { + Query: { + recipes: (_parent, args, context) => + repository.list( + validate(listInputSchema, args.input ?? {}), + context.user?.id ?? null, + ), + recipe: (_parent, args, context) => + repository.get(recipeId(args.id), context.user?.id ?? null), + cookbook: (_parent, args, context) => + repository.list( + validate(listInputSchema, args.input ?? {}), + requireUser(context), + validate(z.enum(['all', 'saved', 'created']), args.scope ?? 'all'), + ), + }, + 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( + validate(recipeInputSchema, args.input), + userId, + ); + }, + updateRecipe: (_parent, args, context) => { + const userId = requireUser(context); + return repository.update( + recipeId(args.id), + validate(recipeInputSchema, args.input), + userId, + ); + }, + deleteRecipe: (_parent, args, context) => + repository.delete(recipeId(args.id), requireUser(context)), + saveRecipe: (_parent, args, context) => + repository.save(recipeId(args.id), requireUser(context)), + unsaveRecipe: (_parent, args, context) => + repository.unsave(recipeId(args.id), requireUser(context)), + }, + } satisfies Pick, 'Query' | 'Mutation'>; +} diff --git a/apps/api/src/features/recipes/recipeValidation.test.ts b/apps/api/src/features/recipes/recipeValidation.test.ts new file mode 100644 index 0000000..e874b52 --- /dev/null +++ b/apps/api/src/features/recipes/recipeValidation.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest'; +import { + listInputSchema, + recipeInputSchema, + validate, +} from './recipeValidation.js'; + +const input = { + title: ' Soup ', + description: '', + category: 'soup', + difficulty: 'easy', + visibility: 'private', + prepMinutes: 0, + cookMinutes: 10, + servings: 2, + ingredients: [{ name: ' Salt ', amount: 0.125, unit: '', note: null }], + instructions: [' Stir '], + tags: [' Quick ', 'quick'], +}; +describe('recipe validation', () => { + it('normalizes text and tags while allowing optional cuisine and image', () => { + const result = validate(recipeInputSchema, input); + expect(result.title).toBe('Soup'); + expect(result.cuisine).toBeNull(); + expect(result.imageUrl).toBeNull(); + expect(result.tags).toEqual(['quick']); + expect(result.instructions).toEqual(['Stir']); + }); + it.each([ + { ...input, category: 'Soup' }, + { ...input, servings: 1.5 }, + { ...input, ingredients: [] }, + { ...input, instructions: [' '] }, + { ...input, imageUrl: 'javascript:alert(1)' }, + { ...input, ingredients: [{ name: 'Salt', amount: 0.00001, unit: '' }] }, + { ...input, ingredients: [{ name: 'Salt', amount: Infinity, unit: '' }] }, + ])('rejects input the database or UI cannot represent', (value) => { + expect(() => validate(recipeInputSchema, value)).toThrow(); + }); + it('uses bounded pagination defaults', () => { + expect(validate(listInputSchema, {})).toMatchObject({ + page: 1, + pageSize: 6, + search: '', + }); + 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 new file mode 100644 index 0000000..deb3ec5 --- /dev/null +++ b/apps/api/src/features/recipes/recipeValidation.ts @@ -0,0 +1,102 @@ +import { GraphQLError } from 'graphql'; +import { z } from 'zod'; +import { uploadedImagePattern } from './imagePaths.js'; + +export const categorySchema = z.enum([ + 'breakfast', + 'lunch', + 'dinner', + 'dessert', + 'soup', +]); +const optionalText = z + .string() + .trim() + .max(200) + .nullish() + .transform((value) => value || null); +export const recipeInputSchema = z.object({ + title: z.string().trim().min(1).max(160), + description: z.string().trim().max(200), + imageUrl: z + .union([ + z.url({ protocol: /^https?$/ }).max(2048), + z.string().regex(uploadedImagePattern), + ]) + .nullish() + .transform((value) => value ?? null), + category: categorySchema, + cuisine: optionalText, + difficulty: z.enum(['easy', 'medium', 'hard']), + visibility: z.enum(['public', 'private']), + prepMinutes: z.number().int().min(0).max(10080), + cookMinutes: z.number().int().min(0).max(10080), + servings: z.number().int().min(1).max(1000), + ingredients: z + .array( + z.object({ + name: z.string().trim().min(1).max(200), + amount: z + .number() + .positive() + .max(99999999.9999) + .refine( + (value) => Math.round(value * 10000) / 10000 === value, + 'Use at most four decimal places.', + ), + unit: z.string().trim().max(50), + note: optionalText, + }), + ) + .min(1) + .max(100), + instructions: z.array(z.string().trim().min(1).max(5000)).min(1).max(100), + tags: z + .array(z.string().trim().toLowerCase().min(1).max(50)) + .max(30) + .transform((values) => [...new Set(values)]), +}); + +export const listInputSchema = z.object({ + search: z + .string() + .trim() + .max(200) + .nullish() + .transform((value) => value ?? ''), + category: categorySchema.nullish(), + maxCookingMinutes: z.number().int().min(0).max(20160).nullish(), + page: z + .number() + .int() + .min(1) + .max(100000) + .nullish() + .transform((value) => value ?? 1), + pageSize: z + .number() + .int() + .min(1) + .max(50) + .nullish() + .transform((value) => value ?? 6), +}); +export type RecipeInput = z.output; +export type ListInput = z.output; + +export function validate(schema: z.ZodType, input: unknown): T { + const result = schema.safeParse(input); + if (!result.success) { + const issue = result.error.issues[0]!; + throw new GraphQLError( + `${issue.path.join('.') || 'input'}: ${issue.message}`, + { + extensions: { code: 'BAD_USER_INPUT' }, + }, + ); + } + return result.data; +} +export function recipeId(value: unknown) { + return validate(z.uuid(), value); +} diff --git a/apps/api/src/generated.ts b/apps/api/src/generated.ts index 8d4e30c..b7d2fec 100644 --- a/apps/api/src/generated.ts +++ b/apps/api/src/generated.ts @@ -14,6 +14,19 @@ export type Scalars = { Float: { input: number; output: number }; }; +export type RecipeDifficulty = 'easy' | 'medium' | 'hard'; + +export type RecipeVisibility = 'public' | 'private'; + +export type RecipeCategory = + | 'breakfast' + | 'lunch' + | 'dinner' + | 'dessert' + | 'soup'; + +export type CookbookScope = 'all' | 'saved' | 'created'; + export type User = { __typename?: 'User'; id: Scalars['ID']['output']; @@ -24,26 +37,74 @@ export type User = { export type AuthPayload = { __typename?: 'AuthPayload'; user: User; - sessionToken: Scalars['String']['output']; }; export type Query = { __typename?: 'Query'; + recipes: RecipePage; + recipe?: Maybe; + cookbook: RecipePage; health: Scalars['String']['output']; currentUser?: Maybe; }; -export type QueryCurrentUserArgs = { - sessionToken: Scalars['String']['input']; +export type QueryRecipesArgs = { + input?: InputMaybe; +}; + +export type QueryRecipeArgs = { + id: Scalars['ID']['input']; +}; + +export type QueryCookbookArgs = { + input?: InputMaybe; + scope?: InputMaybe; }; export type Mutation = { __typename?: 'Mutation'; + createRecipe: Recipe; + updateRecipe: Recipe; + deleteRecipe: Scalars['Boolean']['output']; + saveRecipe: Recipe; + unsaveRecipe: Scalars['Boolean']['output']; + rateRecipe: Recipe; + removeRecipeRating: Scalars['Boolean']['output']; register: AuthPayload; login: AuthPayload; signOut: Scalars['Boolean']['output']; }; +export type MutationCreateRecipeArgs = { + input: RecipeInput; +}; + +export type MutationUpdateRecipeArgs = { + id: Scalars['ID']['input']; + input: RecipeInput; +}; + +export type MutationDeleteRecipeArgs = { + id: Scalars['ID']['input']; +}; + +export type MutationSaveRecipeArgs = { + id: Scalars['ID']['input']; +}; + +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']; @@ -55,8 +116,98 @@ export type MutationLoginArgs = { password: Scalars['String']['input']; }; -export type MutationSignOutArgs = { - sessionToken: Scalars['String']['input']; +export type RecipeAuthor = { + __typename?: 'RecipeAuthor'; + id: Scalars['ID']['output']; + name: Scalars['String']['output']; +}; + +export type Ingredient = { + __typename?: 'Ingredient'; + id: Scalars['ID']['output']; + name: Scalars['String']['output']; + amount: Scalars['Float']['output']; + unit: Scalars['String']['output']; + note?: Maybe; +}; + +export type Instruction = { + __typename?: 'Instruction'; + step: Scalars['Int']['output']; + text: Scalars['String']['output']; +}; + +export type RatingSummary = { + __typename?: 'RatingSummary'; + average: Scalars['Float']['output']; + count: Scalars['Int']['output']; +}; + +export type Recipe = { + __typename?: 'Recipe'; + id: Scalars['ID']['output']; + title: Scalars['String']['output']; + description: Scalars['String']['output']; + category: RecipeCategory; + cuisine?: Maybe; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + imageUrl?: Maybe; + sourceRecipeId?: Maybe; + prepMinutes: Scalars['Int']['output']; + cookMinutes: Scalars['Int']['output']; + servings: Scalars['Int']['output']; + createdAt: Scalars['String']['output']; + updatedAt: Scalars['String']['output']; + author: RecipeAuthor; + ingredients: Array; + instructions: Array; + tags: Array; + rating: RatingSummary; + userRating?: Maybe; + saveCount: Scalars['Int']['output']; + isSaved: Scalars['Boolean']['output']; + isCreatedByCurrentUser: Scalars['Boolean']['output']; +}; + +export type RecipePage = { + __typename?: 'RecipePage'; + items: Array; + totalCount: Scalars['Int']['output']; + totalPages: Scalars['Int']['output']; + page: Scalars['Int']['output']; + pageSize: Scalars['Int']['output']; +}; + +export type RecipeListInput = { + search?: InputMaybe; + category?: InputMaybe; + maxCookingMinutes?: InputMaybe; + page?: InputMaybe; + pageSize?: InputMaybe; +}; + +export type IngredientInput = { + name: Scalars['String']['input']; + amount: Scalars['Float']['input']; + unit: Scalars['String']['input']; + note?: InputMaybe; +}; + +export type RecipeInput = { + title: Scalars['String']['input']; + description: Scalars['String']['input']; + imageUrl?: InputMaybe; + category: RecipeCategory; + cuisine?: InputMaybe; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + prepMinutes: Scalars['Int']['input']; + cookMinutes: Scalars['Int']['input']; + servings: Scalars['Int']['input']; + ingredients: Array; + instructions: Array; + tags: Array; }; export type ResolverTypeWrapper = Promise | T; @@ -178,6 +329,10 @@ export type DirectiveResolverFn< /** Mapping between all available schema types and the resolvers types */ export type ResolversTypes = { + RecipeDifficulty: RecipeDifficulty; + RecipeVisibility: RecipeVisibility; + RecipeCategory: RecipeCategory; + CookbookScope: CookbookScope; User: ResolverTypeWrapper; ID: ResolverTypeWrapper; String: ResolverTypeWrapper; @@ -185,6 +340,17 @@ export type ResolversTypes = { Query: ResolverTypeWrapper>; Mutation: ResolverTypeWrapper>; Boolean: ResolverTypeWrapper; + Int: ResolverTypeWrapper; + RecipeAuthor: ResolverTypeWrapper; + Ingredient: ResolverTypeWrapper; + Float: ResolverTypeWrapper; + Instruction: ResolverTypeWrapper; + RatingSummary: ResolverTypeWrapper; + Recipe: ResolverTypeWrapper; + RecipePage: ResolverTypeWrapper; + RecipeListInput: RecipeListInput; + IngredientInput: IngredientInput; + RecipeInput: RecipeInput; }; /** Mapping between all available schema types and the resolvers parents */ @@ -196,6 +362,17 @@ 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; + RatingSummary: RatingSummary; + Recipe: Recipe; + RecipePage: RecipePage; + RecipeListInput: RecipeListInput; + IngredientInput: IngredientInput; + RecipeInput: RecipeInput; }; export type UserResolvers< @@ -214,7 +391,6 @@ export type AuthPayloadResolvers< ResolversParentTypes['AuthPayload'] = ResolversParentTypes['AuthPayload'], > = { user?: Resolver; - sessionToken?: Resolver; }; export type QueryResolvers< @@ -222,12 +398,29 @@ export type QueryResolvers< ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query'], > = { + recipes?: Resolver< + ResolversTypes['RecipePage'], + ParentType, + ContextType, + Partial + >; + recipe?: Resolver< + Maybe, + ParentType, + ContextType, + RequireFields + >; + cookbook?: Resolver< + ResolversTypes['RecipePage'], + ParentType, + ContextType, + Partial + >; health?: Resolver; currentUser?: Resolver< Maybe, ParentType, - ContextType, - RequireFields + ContextType >; }; @@ -236,6 +429,48 @@ export type MutationResolvers< ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation'], > = { + createRecipe?: Resolver< + ResolversTypes['Recipe'], + ParentType, + ContextType, + RequireFields + >; + updateRecipe?: Resolver< + ResolversTypes['Recipe'], + ParentType, + ContextType, + RequireFields + >; + deleteRecipe?: Resolver< + ResolversTypes['Boolean'], + ParentType, + ContextType, + RequireFields + >; + saveRecipe?: Resolver< + ResolversTypes['Recipe'], + ParentType, + ContextType, + RequireFields + >; + unsaveRecipe?: Resolver< + ResolversTypes['Boolean'], + ParentType, + ContextType, + RequireFields + >; + rateRecipe?: Resolver< + ResolversTypes['Recipe'], + ParentType, + ContextType, + RequireFields + >; + removeRecipeRating?: Resolver< + ResolversTypes['Boolean'], + ParentType, + ContextType, + RequireFields + >; register?: Resolver< ResolversTypes['AuthPayload'], ParentType, @@ -248,17 +483,127 @@ export type MutationResolvers< ContextType, RequireFields >; - signOut?: Resolver< + signOut?: Resolver; +}; + +export type RecipeAuthorResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['RecipeAuthor'] = ResolversParentTypes['RecipeAuthor'], +> = { + id?: Resolver; + name?: Resolver; +}; + +export type IngredientResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['Ingredient'] = ResolversParentTypes['Ingredient'], +> = { + id?: Resolver; + name?: Resolver; + amount?: Resolver; + unit?: Resolver; + note?: Resolver, ParentType, ContextType>; +}; + +export type InstructionResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['Instruction'] = ResolversParentTypes['Instruction'], +> = { + step?: Resolver; + text?: Resolver; +}; + +export type RatingSummaryResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['RatingSummary'] = ResolversParentTypes['RatingSummary'], +> = { + average?: Resolver; + count?: Resolver; +}; + +export type RecipeResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['Recipe'] = ResolversParentTypes['Recipe'], +> = { + id?: Resolver; + title?: Resolver; + description?: Resolver; + category?: Resolver< + ResolversTypes['RecipeCategory'], + ParentType, + ContextType + >; + cuisine?: Resolver, ParentType, ContextType>; + difficulty?: Resolver< + ResolversTypes['RecipeDifficulty'], + ParentType, + ContextType + >; + visibility?: Resolver< + ResolversTypes['RecipeVisibility'], + ParentType, + ContextType + >; + imageUrl?: Resolver, ParentType, ContextType>; + sourceRecipeId?: Resolver< + Maybe, + ParentType, + ContextType + >; + prepMinutes?: Resolver; + cookMinutes?: Resolver; + servings?: Resolver; + createdAt?: Resolver; + updatedAt?: Resolver; + author?: Resolver; + ingredients?: Resolver< + Array, + ParentType, + ContextType + >; + instructions?: Resolver< + Array, + ParentType, + ContextType + >; + tags?: Resolver, ParentType, ContextType>; + rating?: Resolver; + userRating?: Resolver, ParentType, ContextType>; + saveCount?: Resolver; + isSaved?: Resolver; + isCreatedByCurrentUser?: Resolver< ResolversTypes['Boolean'], ParentType, - ContextType, - RequireFields + ContextType >; }; +export type RecipePageResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['RecipePage'] = ResolversParentTypes['RecipePage'], +> = { + items?: Resolver, ParentType, ContextType>; + totalCount?: Resolver; + totalPages?: Resolver; + page?: Resolver; + pageSize?: Resolver; +}; + export type Resolvers = { User?: UserResolvers; AuthPayload?: AuthPayloadResolvers; Query?: QueryResolvers; Mutation?: MutationResolvers; + RecipeAuthor?: RecipeAuthorResolvers; + Ingredient?: IngredientResolvers; + Instruction?: InstructionResolvers; + RatingSummary?: RatingSummaryResolvers; + Recipe?: RecipeResolvers; + RecipePage?: RecipePageResolvers; }; diff --git a/apps/api/src/schema.graphql b/apps/api/src/schema.graphql index c2cb462..68fd67a 100644 --- a/apps/api/src/schema.graphql +++ b/apps/api/src/schema.graphql @@ -1,3 +1,28 @@ +enum RecipeDifficulty { + easy + medium + hard +} + +enum RecipeVisibility { + public + private +} + +enum RecipeCategory { + breakfast + lunch + dinner + dessert + soup +} + +enum CookbookScope { + all + saved + created +} + type User { id: ID! name: String! @@ -6,16 +31,105 @@ type User { type AuthPayload { user: User! - sessionToken: String! } type Query { + recipes(input: RecipeListInput): RecipePage! + recipe(id: ID!): Recipe + cookbook(input: RecipeListInput, scope: CookbookScope): RecipePage! health: String! - currentUser(sessionToken: String!): User + currentUser: User } type Mutation { + createRecipe(input: RecipeInput!): Recipe! + updateRecipe(id: ID!, input: RecipeInput!): Recipe! + 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(sessionToken: String!): Boolean! + signOut: Boolean! +} + +type RecipeAuthor { + id: ID! + name: String! +} +type Ingredient { + id: ID! + name: String! + amount: Float! + unit: String! + note: String +} +type Instruction { + step: Int! + text: String! +} +type RatingSummary { + average: Float! + count: Int! +} +type Recipe { + id: ID! + title: String! + description: String! + category: RecipeCategory! + cuisine: String + difficulty: RecipeDifficulty! + visibility: RecipeVisibility! + imageUrl: String + sourceRecipeId: ID + prepMinutes: Int! + cookMinutes: Int! + servings: Int! + createdAt: String! + updatedAt: String! + author: RecipeAuthor! + ingredients: [Ingredient!]! + instructions: [Instruction!]! + tags: [String!]! + rating: RatingSummary! + userRating: Int + saveCount: Int! + isSaved: Boolean! + isCreatedByCurrentUser: Boolean! +} +type RecipePage { + items: [Recipe!]! + totalCount: Int! + totalPages: Int! + page: Int! + pageSize: Int! +} +input RecipeListInput { + search: String + category: RecipeCategory + maxCookingMinutes: Int + page: Int + pageSize: Int +} +input IngredientInput { + name: String! + amount: Float! + unit: String! + note: String +} +input RecipeInput { + title: String! + description: String! + imageUrl: String + category: RecipeCategory! + cuisine: String + difficulty: RecipeDifficulty! + visibility: RecipeVisibility! + prepMinutes: Int! + cookMinutes: Int! + servings: Int! + ingredients: [IngredientInput!]! + instructions: [String!]! + tags: [String!]! } 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/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/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/assets/illustrations/not-found-chef-hat.png b/apps/web/src/assets/illustrations/not-found-chef-hat.png deleted file mode 100644 index e12b2d4..0000000 Binary files a/apps/web/src/assets/illustrations/not-found-chef-hat.png and /dev/null differ diff --git a/apps/web/src/assets/illustrations/not-found-chef-hat.webp b/apps/web/src/assets/illustrations/not-found-chef-hat.webp new file mode 100644 index 0000000..688dcc1 Binary files /dev/null and b/apps/web/src/assets/illustrations/not-found-chef-hat.webp differ diff --git a/apps/web/src/assets/recipe-fallback.png b/apps/web/src/assets/recipe-fallback.png deleted file mode 100644 index b141e8e..0000000 Binary files a/apps/web/src/assets/recipe-fallback.png and /dev/null differ diff --git a/apps/web/src/assets/recipe-fallback.webp b/apps/web/src/assets/recipe-fallback.webp new file mode 100644 index 0000000..6948b1a Binary files /dev/null and b/apps/web/src/assets/recipe-fallback.webp differ diff --git a/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx b/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx index 9d7584c..3c7b609 100644 --- a/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx +++ b/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx @@ -1,7 +1,7 @@ import { useState, type ComponentPropsWithoutRef, type ReactNode } from 'react'; import { Link, useLocation } from 'react-router-dom'; -import fallbackRecipeImage from '../../../assets/recipe-fallback.png'; +import fallbackRecipeImage from '../../../assets/recipe-fallback.webp'; import { HeartIcon } from '../../../icons/actions'; import Button from '../../ui/Button/Button'; import ConfirmationDialog from '../../ui/ConfirmationDialog/ConfirmationDialog'; @@ -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/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/components/shell/SiteHeader/SiteHeader.test.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx index 37844c4..accf529 100644 --- a/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx @@ -84,8 +84,6 @@ describe('SiteHeader authentication', () => { }); it('updates the header after signing out', async () => { - localStorage.setItem('recipe-platform-session-token', 'session-123'); - useAppStore.setState({ currentUser: authenticatedUser, }); @@ -110,8 +108,23 @@ describe('SiteHeader authentication', () => { ).toBeInTheDocument(); }); - expect(signOutUser).toHaveBeenCalledWith('session-123'); + expect(signOutUser).toHaveBeenCalledWith(); expect(useAppStore.getState().currentUser).toBeNull(); }); + it('shows a recoverable error when cookie logout fails', async () => { + useAppStore.setState({ + currentUser: authenticatedUser, + sessionStatus: 'authenticated', + }); + vi.mocked(signOutUser).mockRejectedValueOnce(new Error('Offline')); + renderHeader(); + await userEvent + .setup() + .click(screen.getByRole('button', { name: 'Sign out' })); + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Unable to sign out', + ); + expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); + }); }); diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx index 6b68e13..9fa2d73 100644 --- a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx @@ -10,6 +10,7 @@ import { } from '../../../icons/navigation'; import { useAppStore } from '../../../store'; import Button from '../../ui/Button/Button'; +import FeedbackMessage from '../../ui/FeedbackMessage/FeedbackMessage'; import IconButton from '../../ui/IconButton/IconButton'; import './SiteHeader.css'; import LogoMark from '../../brand/LogoMark/LogoMark'; @@ -24,6 +25,7 @@ const pages = [ function SiteHeader() { const [menuOpen, setMenuOpen] = useState(false); + const [logoutError, setLogoutError] = useState(''); const navigate = useNavigate(); const currentUser = useAppStore((state) => state.currentUser); @@ -32,9 +34,14 @@ function SiteHeader() { const closeMenu = () => setMenuOpen(false); const handleSignOut = async () => { - await signOut(); - closeMenu(); - navigate('/'); + setLogoutError(''); + try { + await signOut(); + closeMenu(); + navigate('/'); + } catch { + setLogoutError('Unable to sign out. Please try again.'); + } }; return ( @@ -87,6 +94,9 @@ function SiteHeader() { ))}
+ {logoutError && ( + {logoutError} + )} {currentUser ? ( <> 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/auth/AuthPages.test.tsx b/apps/web/src/features/auth/AuthPages.test.tsx index 856ccdb..f8ca789 100644 --- a/apps/web/src/features/auth/AuthPages.test.tsx +++ b/apps/web/src/features/auth/AuthPages.test.tsx @@ -40,7 +40,6 @@ describe('authentication pages', () => { it('submits a short existing password on login', async () => { vi.mocked(loginUser).mockResolvedValue({ user: authenticatedUser, - sessionToken: 'session-123', }); const user = userEvent.setup(); renderAuthPage('/login'); @@ -93,7 +92,6 @@ describe('authentication pages', () => { it('registers a user and navigates to Explore', async () => { vi.mocked(registerUser).mockResolvedValue({ user: authenticatedUser, - sessionToken: 'session-123', }); const user = userEvent.setup(); @@ -128,15 +126,12 @@ describe('authentication pages', () => { expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); - expect(localStorage.getItem('recipe-platform-session-token')).toBe( - 'session-123', - ); + expect(localStorage.getItem('recipe-platform-session-token')).toBeNull(); }); it('logs in and navigates to Explore', async () => { vi.mocked(loginUser).mockResolvedValue({ user: authenticatedUser, - sessionToken: 'session-456', }); const user = userEvent.setup(); @@ -199,7 +194,6 @@ describe('authentication pages', () => { expect(screen.getByRole('button')).toBeEnabled(); request.mockResolvedValueOnce({ user: authenticatedUser, - sessionToken: 'retry-session', }); await user.click(screen.getByRole('button')); expect( @@ -211,10 +205,7 @@ describe('authentication pages', () => { it.each(['/login', '/register'] as const)( 'prevents duplicate submissions on %s', async (route) => { - let resolve!: (value: { - user: typeof authenticatedUser; - sessionToken: string; - }) => void; + let resolve!: (value: { user: typeof authenticatedUser }) => void; const request = vi.mocked(route === '/login' ? loginUser : registerUser); request.mockReturnValueOnce( new Promise((done) => { @@ -236,7 +227,7 @@ describe('authentication pages', () => { expect(screen.getByRole('button')).toBeDisabled(); await user.click(screen.getByRole('button')); expect(request).toHaveBeenCalledTimes(1); - resolve({ user: authenticatedUser, sessionToken: 'session-123' }); + resolve({ user: authenticatedUser }); expect( await screen.findByRole('heading', { name: 'Explore' }), ).toBeInTheDocument(); diff --git a/apps/web/src/features/auth/RequireAuth.test.tsx b/apps/web/src/features/auth/RequireAuth.test.tsx index 3422aea..a1d760b 100644 --- a/apps/web/src/features/auth/RequireAuth.test.tsx +++ b/apps/web/src/features/auth/RequireAuth.test.tsx @@ -15,7 +15,6 @@ vi.mock('./authApi', () => ({ signOutUser: vi.fn(), })); const user = { id: 'user-123', name: 'Hasan', email: 'hasan@example.com' }; -const tokenKey = 'recipe-platform-session-token'; function LocationProbe() { const location = useLocation(); return ( @@ -44,6 +43,7 @@ function pendingSession() { } beforeEach(() => { vi.resetAllMocks(); + vi.mocked(getCurrentUser).mockResolvedValue(null); localStorage.clear(); useAppStore.setState({ currentUser: null, sessionStatus: 'restoring' }); }); @@ -64,7 +64,6 @@ describe('protected routes with session restoration', () => { ])( 'waits on refresh of %s and renders after validation', async (path, title) => { - localStorage.setItem(tokenKey, 'valid-token'); const resolve = pendingSession(); renderApp(path!); expect(screen.getByText('Restoring your session...')).toHaveTextContent( @@ -85,7 +84,6 @@ describe('protected routes with session restoration', () => { }, ); it('redirects only after the API confirms expiry', async () => { - localStorage.setItem(tokenKey, 'expired-token'); const resolve = pendingSession(); renderApp('/cookbook'); expect(screen.getByTestId('location')).toHaveTextContent('/cookbook'); @@ -93,10 +91,8 @@ describe('protected routes with session restoration', () => { expect( await screen.findByRole('heading', { name: 'Log in' }), ).toBeInTheDocument(); - expect(localStorage.getItem(tokenKey)).toBeNull(); }); - it('keeps the token and protected URL during an outage and permits retry', async () => { - localStorage.setItem(tokenKey, 'valid-token'); + it('keeps the protected URL during a cookie-session outage and permits retry', async () => { vi.mocked(getCurrentUser).mockRejectedValue(new Error('Offline')); renderApp('/recipes/new'); expect(await screen.findByRole('alert')).toHaveTextContent( @@ -106,7 +102,7 @@ describe('protected routes with session restoration', () => { expect( screen.queryByRole('heading', { name: 'Add Recipe' }), ).not.toBeInTheDocument(); - expect(localStorage.getItem(tokenKey)).toBe('valid-token'); + vi.mocked(getCurrentUser).mockResolvedValue(user); await userEvent .setup() @@ -120,11 +116,9 @@ describe('protected routes with session restoration', () => { async (register) => { vi.mocked(loginUser).mockResolvedValue({ user, - sessionToken: 'new-token', }); vi.mocked(registerUser).mockResolvedValue({ user, - sessionToken: 'new-token', }); const interaction = userEvent.setup(); renderApp('/cookbook?view=saved#recipes'); @@ -152,7 +146,6 @@ describe('protected routes with session restoration', () => { }, ); it('leaves Explore public during session restoration', () => { - localStorage.setItem(tokenKey, 'valid-token'); pendingSession(); renderApp('/'); expect( diff --git a/apps/web/src/features/auth/authApi.test.ts b/apps/web/src/features/auth/authApi.test.ts index 0c3b28d..d4cacd2 100644 --- a/apps/web/src/features/auth/authApi.test.ts +++ b/apps/web/src/features/auth/authApi.test.ts @@ -1,5 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { getCurrentUser, loginUser, registerUser } from './authApi'; +import { + getCurrentUser, + loginUser, + registerUser, + signOutUser, +} from './authApi'; afterEach(() => vi.unstubAllGlobals()); const requests = [ @@ -8,6 +13,21 @@ const requests = [ ]; describe('authentication API errors', () => { + it('uses browser credentials and sends no session-token variables', async () => { + const fetch = vi + .fn() + .mockResolvedValueOnce(Response.json({ data: { currentUser: null } })) + .mockResolvedValueOnce(Response.json({ data: { signOut: true } })); + vi.stubGlobal('fetch', fetch); + await getCurrentUser(); + await signOutUser(); + for (const [, options] of fetch.mock.calls) { + expect(options.credentials).toBe('same-origin'); + expect(options.headers['X-Requested-With']).toBe('recipe-platform'); + expect(JSON.parse(options.body).variables).toEqual({}); + expect(options.body).not.toContain('sessionToken'); + } + }); it.each(requests)('translates network failures', async (request) => { vi.stubGlobal( 'fetch', @@ -82,6 +102,6 @@ describe('authentication API errors', () => { }), ), ); - await expect(getCurrentUser('session-123')).rejects.toThrow(); + await expect(getCurrentUser()).rejects.toThrow(); }); }); diff --git a/apps/web/src/features/auth/authApi.ts b/apps/web/src/features/auth/authApi.ts index f644834..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,39 +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' }, - 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, @@ -61,10 +43,9 @@ export async function registerUser( export async function loginUser(email: string, password: string) { return (await graphqlRequest(LoginDocument, { email, password })).login; } -export async function getCurrentUser(sessionToken: string) { - return (await graphqlRequest(CurrentUserDocument, { sessionToken })) - .currentUser; +export async function getCurrentUser() { + return (await graphqlRequest(CurrentUserDocument, {})).currentUser; } -export async function signOutUser(sessionToken: string) { - return (await graphqlRequest(SignOutDocument, { sessionToken })).signOut; +export async function signOutUser() { + return (await graphqlRequest(SignOutDocument, {})).signOut; } 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 deleted file mode 100644 index 123eaa3..0000000 --- a/apps/web/src/features/cookbook/mockCookbookQuery.test.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { INITIAL_SAVED_RECIPE_IDS } from '../../store'; - -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 2a3d823..0000000 --- a/apps/web/src/features/cookbook/mockCookbookQuery.ts +++ /dev/null @@ -1,101 +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, CookbookSort } from './cookbookBrowseState'; - -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> = - { - '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/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.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 23b6b57..0000000 --- a/apps/web/src/features/explore/mockExploreQuery.ts +++ /dev/null @@ -1,126 +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, ExploreSort } from './exploreBrowseState'; - -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/not-found/NotFoundPage.tsx b/apps/web/src/features/not-found/NotFoundPage.tsx index fe0e204..ce4c6d9 100644 --- a/apps/web/src/features/not-found/NotFoundPage.tsx +++ b/apps/web/src/features/not-found/NotFoundPage.tsx @@ -2,7 +2,7 @@ import { useNavigate } from 'react-router-dom'; import Button from '../../components/ui/Button/Button'; import LinkButton from '../../components/ui/LinkButton/LinkButton'; -import chefHatIllustration from '../../assets/illustrations/not-found-chef-hat.png'; +import chefHatIllustration from '../../assets/illustrations/not-found-chef-hat.webp'; import './NotFoundPage.css'; 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 68a2a1b..f90b9fa 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx @@ -1,206 +1,141 @@ -import '@testing-library/jest-dom/vitest'; -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, 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', - ); +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.getByRole('button', { name: 'Rate Recipe' })).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('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'); +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(); +}); - 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('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 062632d..a158302 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx @@ -1,22 +1,22 @@ -import { useMemo, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { useLocation, useNavigate, useParams } from 'react-router-dom'; -import fallbackRecipeImage from '../../assets/recipe-fallback.png'; +import fallbackRecipeImage from '../../assets/recipe-fallback.webp'; 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'; -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 +24,19 @@ 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, + changeRecipeRating, + 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 +86,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 +98,29 @@ 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 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); 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); + const [ratingOpen, setRatingOpen] = useState(false); + const [pendingRating, setPendingRating] = useState(recipe.userRating ?? 0); - // 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 +175,63 @@ 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; + setBusy(true); + 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', + message: recipeErrorMessage(error), + }); + } finally { + busyRef.current = false; + if (mounted.current) 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 ( @@ -273,7 +268,11 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { ] .filter(Boolean) .join(' ')} - src={recipe.imageUrl ?? fallbackRecipeImage} + src={ + recipe.imageUrl + ? recipeImageUrl(recipe.imageUrl) + : fallbackRecipeImage + } alt={recipe.imageUrl ? recipe.title : ''} />
@@ -307,10 +306,31 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { {!isPrivate ? ( - + canSaveOrRate ? ( + + ) : ( +
+ + + {isOwner + ? 'You cannot rate your own recipe.' + : 'Sign in to rate this recipe.'} + +
+ ) ) : null} @@ -366,15 +386,23 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
{isOwner ? ( - - + <> + + + + ) : canSaveOrRate ? ( <> ) : null} @@ -607,49 +627,67 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { > You can save this recipe again later. - - setRatingDialogOpen(false)} - footer={ - <> - {userRating ? ( - - ) : null} - - - - - - } - > - - ) : null} - {feedback ? ( + setConfirmDeleteOpen(false)} + > + This action cannot be undone. + + + {recipe.userRating != null && ( + + )} + + + + } + > +
+ +
+ {feedback?.tone === 'error' &&

{feedback.message}

} +
+ {feedback && !(ratingOpen && feedback.tone === 'error') ? (
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,14 +721,19 @@ function RecipeDetailPage() { Back to Explore} /> ); } - return ; + return ( + <> + + + + ); } export default RecipeDetailPage; diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx index efbbb31..97335cd 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -1,13 +1,41 @@ 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, beforeEach, describe, expect, it, vi } from 'vitest'; +import { useAppStore } from '../../store'; +import { apiUser } from '../../test/recipeApiFixtures'; +import { useRecipeChanges } from './recipeApi'; +import { act } from '@testing-library/react'; 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()); +beforeEach(() => + useAppStore.setState({ + currentUser: apiUser, + sessionStatus: 'authenticated', + }), +); describe('RecipeCreatePage', () => { it('exposes the recipe fields through accessible labels', () => { - render(); + mount(); expect( screen.getByRole('heading', { name: 'Add Recipe' }), @@ -21,13 +49,15 @@ describe('RecipeCreatePage', () => { expect( screen.getByRole('group', { name: /Visibility/ }), ).toBeInTheDocument(); - expect(screen.getByLabelText(/Recipe image/)).toBeInTheDocument(); + expect(screen.getByLabelText('Recipe image')).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 +65,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 +78,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 +88,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 +108,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 +164,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 +214,135 @@ 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 } }; }); + 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'); +}); - it('shows local success feedback for a valid recipe', async () => { - const user = userEvent.setup(); - - render(); +it('preserves unsaved edits when another mutation invalidates recipe lists', async () => { + const fetch = mockRecipeFetch(() => ({ + data: { recipe: { ...apiRecipe, isCreatedByCurrentUser: true } }, + })); + mount('/recipes/' + apiRecipe.id + '/edit'); + await screen.findByRole('heading', { name: 'Edit Recipe' }); + const title = screen.getByLabelText(/Recipe title/); + fireEvent.change(title, { target: { value: 'Unsaved edits' } }); + act(() => + useRecipeChanges.setState((state) => ({ revision: state.revision + 1 })), + ); + expect(title).toHaveValue('Unsaved edits'); + expect(fetch).toHaveBeenCalledTimes(1); +}); - 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' })); +it('shows not-found for malformed edit IDs', async () => { + const fetch = mockRecipeFetch(() => { + throw new Error('Unexpected fetch'); + }); + mount('/recipes/abc/edit'); + expect( + await screen.findByText( + 'This recipe does not exist or is not available to you.', + ), + ).toBeInTheDocument(); + expect(screen.queryByText('You can only edit your own recipes.')).toBeNull(); + expect(fetch).not.toHaveBeenCalled(); +}); - expect(screen.getByText('Recipe ready to publish')).toBeInTheDocument(); - expect( - screen.getByText(/No data was sent to a server/), - ).toBeInTheDocument(); +it('does not fetch or reset the new recipe form after list invalidation', () => { + const fetch = mockRecipeFetch(() => { + throw new Error('Unexpected fetch'); }); + mount(); + const title = screen.getByLabelText(/Recipe title/); + fireEvent.change(title, { target: { value: 'New draft' } }); + act(() => + useRecipeChanges.setState((state) => ({ revision: state.revision + 1 })), + ); + expect(title).toHaveValue('New draft'); + expect(fetch).not.toHaveBeenCalled(); }); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index 3709c67..0f82757 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,18 @@ 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 RecipeImageField from './RecipeImageField'; import './RecipeCreatePage.css'; @@ -31,6 +36,8 @@ type RecipeErrors = { title?: string; description?: string; cookingTime?: string; + prepTime?: string; + difficulty?: string; servings?: string; category?: string; visibility?: string; @@ -45,51 +52,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 +69,46 @@ 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 [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( + 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 +287,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 +294,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 +320,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 +346,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 +359,9 @@ function RecipeCreatePage() { return nextErrors; } - function handleSubmit(event: FormEvent) { + async function handleSubmit(event: FormEvent) { event.preventDefault(); + if (busyRef.current || imagePending) return; const nextErrors = validateForm(); setErrors(nextErrors); @@ -456,6 +370,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 +401,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, + 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 +445,9 @@ function RecipeCreatePage() { >

Share with the community

-

Add Recipe

+

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

Share your favorite recipe with the community.

@@ -506,14 +458,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 +515,13 @@ function RecipeCreatePage() {
-
- {imagePreviewUrl ? ( -
- Selected recipe -
- - {imageFile?.name ?? imageName} - - -
-
- ) : ( - - )} - - Upload a JPG, PNG, or WebP image up to 5 MB. - - {errors.image && ( - - )} -
+ - - - - - } - > -
- setCroppedAreaPixels(area)} - /> -
- -
-
+ { + setPrepTime(event.target.value); + clearError('prepTime'); + }} + /> + Lunch +
@@ -771,15 +642,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 +731,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 +849,44 @@ function RecipeCreatePage() { > Save draft - +
- + ); } +function RecipeEditPage({ id }: { id: string }) { + const load = useCallback( + (signal: AbortSignal) => getRecipe(id, signal), + [id], + ); + const query = useRecipeQuery(id, load, { refreshOnMutation: false }); + if (query.loading || query.error) + return ; + if (!query.data) + return ( +
+

Recipe unavailable

+

This recipe does not exist or is not available to you.

+ Back to My Cookbook +
+ ); + if (!query.data.isCreatedByCurrentUser) + return ( +
+

Cannot edit recipe

+

You can only edit your own recipes.

+ Back to My Cookbook +
+ ); + return ; +} +function RecipeCreatePage() { + const { id } = useParams(); + return id ? : ; +} export default RecipeCreatePage; 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..0a205f4 --- /dev/null +++ b/apps/web/src/features/recipes/RecipeImageField.tsx @@ -0,0 +1,200 @@ +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'); + const scale = Math.min(1, 1600 / Math.max(area.width, area.height)); + canvas.width = Math.max(1, Math.round(area.width * scale)); + canvas.height = Math.max(1, Math.round(area.height * scale)); + 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/RecipeQueryStatus.tsx b/apps/web/src/features/recipes/RecipeQueryStatus.tsx new file mode 100644 index 0000000..7eff45c --- /dev/null +++ b/apps/web/src/features/recipes/RecipeQueryStatus.tsx @@ -0,0 +1,25 @@ +import Button from '../../components/ui/Button/Button'; + +export default function RecipeQueryStatus({ + loading, + error, + retry, + refreshError, + label = 'Loading recipes…', +}: { + loading: boolean; + error?: string; + retry: () => void; + refreshError?: string; + label?: string; +}) { + if (loading) return

{label}

; + if (error || refreshError) + return ( +
+

{refreshError ? `Could not refresh: ${refreshError}` : 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..ecbfd8e --- /dev/null +++ b/apps/web/src/features/recipes/recipeApi.ts @@ -0,0 +1,100 @@ +import { create } from 'zustand'; +import { z } from 'zod'; +import { + RecipesDocument, + CookbookDocument, + RecipeDocument, + CreateRecipeDocument, + UpdateRecipeDocument, + DeleteRecipeDocument, + SaveRecipeDocument, + UnsaveRecipeDocument, + RateRecipeDocument, + RemoveRecipeRatingDocument, + 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 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 = { + 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/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 new file mode 100644 index 0000000..2d4a755 --- /dev/null +++ b/apps/web/src/features/recipes/recipeImages.ts @@ -0,0 +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.'); + 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, + }, + ); + } 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: '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] ?? 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); + } +} 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 new file mode 100644 index 0000000..270b5f7 --- /dev/null +++ b/apps/web/src/features/recipes/useRecipeQuery.ts @@ -0,0 +1,57 @@ +import { useEffect, useState } from 'react'; +import { useAppStore } from '../../store'; +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) => + 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({ identity, key: requestKey, hasData: true, data }); + }, + (error: unknown) => { + if (!controller.signal.aborted) + setState((previous) => ({ + ...(previous.identity === identity ? previous : { hasData: false }), + identity, + key: requestKey, + error: recipeErrorMessage(error), + })); + }, + ); + return () => controller.abort(); + }, [identity, requestKey, load, waiting]); + const current = !waiting && state.identity === identity ? state : undefined; + const hasData = current?.hasData ?? false; + return { + 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/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/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/store.test.ts b/apps/web/src/store.test.ts index 66613e6..5b5a12f 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -1,119 +1,68 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; - import { getCurrentUser, loginUser, signOutUser, } from './features/auth/authApi'; import { useAppStore } from './store'; - vi.mock('./features/auth/authApi', () => ({ loginUser: vi.fn(), registerUser: vi.fn(), getCurrentUser: vi.fn(), signOutUser: vi.fn(), })); - -const authenticatedUser = { - id: 'user-123', - name: 'Hasan', - email: 'hasan@example.com', -}; - -const SESSION_TOKEN_KEY = 'recipe-platform-session-token'; - -describe('authentication store', () => { - beforeEach(() => { - vi.clearAllMocks(); - localStorage.clear(); - - useAppStore.setState({ - search: '', - currentUser: null, - sessionStatus: 'restoring', - }); - }); - - it('restores the current user from a stored session', async () => { - localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); - - vi.mocked(getCurrentUser).mockResolvedValue(authenticatedUser); - +const user = { id: 'user-123', name: 'Hasan', email: 'hasan@example.com' }; +const legacyKey = 'recipe-platform-session-token'; +beforeEach(() => { + vi.resetAllMocks(); + localStorage.clear(); + useAppStore.setState({ currentUser: null, sessionStatus: 'restoring' }); +}); +describe('cookie authentication store', () => { + it('restores through the browser cookie without reading a token', async () => { + localStorage.setItem(legacyKey, 'old-token'); + vi.mocked(getCurrentUser).mockResolvedValue(user); await useAppStore.getState().restoreSession(); - - expect(getCurrentUser).toHaveBeenCalledWith('session-123'); - - expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); - - expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBe('session-123'); + expect(getCurrentUser).toHaveBeenCalledWith(); + expect(useAppStore.getState().currentUser).toEqual(user); + expect(localStorage.getItem(legacyKey)).toBeNull(); }); - - it('removes an invalid session', async () => { - localStorage.setItem(SESSION_TOKEN_KEY, 'expired-session'); - + it('becomes anonymous when the cookie is absent or expired', async () => { vi.mocked(getCurrentUser).mockResolvedValue(null); - await useAppStore.getState().restoreSession(); - - expect(useAppStore.getState().currentUser).toBeNull(); - - expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBeNull(); + expect(useAppStore.getState().sessionStatus).toBe('anonymous'); }); - - it.each(['Network error', 'API unavailable'])( - 'keeps the token after %s and restores on retry', - async (message) => { - localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); - vi.mocked(getCurrentUser).mockRejectedValueOnce(new Error(message)); - await useAppStore.getState().restoreSession(); - expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBe('session-123'); - expect(useAppStore.getState().currentUser).toBeNull(); - vi.mocked(getCurrentUser).mockResolvedValueOnce(authenticatedUser); - await useAppStore.getState().restoreSession(); - expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); - }, - ); - - it('signs out and removes the session', async () => { - localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); - - useAppStore.setState({ - currentUser: authenticatedUser, - }); - + it('can retry cookie restoration after a network error', async () => { + vi.mocked(getCurrentUser).mockRejectedValueOnce(new Error('Offline')); + await useAppStore.getState().restoreSession(); + expect(useAppStore.getState().sessionStatus).toBe('error'); + vi.mocked(getCurrentUser).mockResolvedValueOnce(user); + await useAppStore.getState().restoreSession(); + expect(useAppStore.getState().currentUser).toEqual(user); + }); + it('logs in without storing session credentials', async () => { + vi.mocked(loginUser).mockResolvedValue({ user }); + await useAppStore.getState().login(user.email, 'secret'); + expect(useAppStore.getState().currentUser).toEqual(user); + expect(localStorage.length).toBe(0); + }); + it('waits for server logout before clearing authentication', async () => { + useAppStore.setState({ currentUser: user, sessionStatus: 'authenticated' }); vi.mocked(signOutUser).mockResolvedValue(true); - await useAppStore.getState().signOut(); - - expect(signOutUser).toHaveBeenCalledWith('session-123'); - - expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBeNull(); - - expect(useAppStore.getState().currentUser).toBeNull(); + expect(signOutUser).toHaveBeenCalledWith(); + expect(useAppStore.getState().sessionStatus).toBe('anonymous'); }); - - it('clears local authentication even when sign-out fails', async () => { - localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); - - useAppStore.setState({ - currentUser: authenticatedUser, - }); - - vi.mocked(signOutUser).mockRejectedValue(new Error('Network error')); - - await expect(useAppStore.getState().signOut()).rejects.toThrow( - 'Network error', - ); - - expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBeNull(); - - expect(useAppStore.getState().currentUser).toBeNull(); + it('does not claim logout succeeded when the server is unavailable', async () => { + useAppStore.setState({ currentUser: user, sessionStatus: 'authenticated' }); + vi.mocked(signOutUser).mockRejectedValue(new Error('Offline')); + await expect(useAppStore.getState().signOut()).rejects.toThrow('Offline'); + expect(useAppStore.getState().currentUser).toEqual(user); }); it.each(['login', 'signOut'] as const)( - 'ignores restoration that finishes after %s', + 'ignores stale restoration after %s', async (action) => { - localStorage.setItem(SESSION_TOKEN_KEY, 'old-token'); - let resolve!: (value: typeof authenticatedUser | null) => void; + let resolve!: (value: typeof user | null) => void; vi.mocked(getCurrentUser).mockReturnValueOnce( new Promise((done) => { resolve = done; @@ -121,28 +70,17 @@ describe('authentication store', () => { ); const restoration = useAppStore.getState().restoreSession(); if (action === 'login') { - vi.mocked(loginUser).mockResolvedValueOnce({ - user: authenticatedUser, - sessionToken: 'new-token', - }); - await useAppStore - .getState() - .login(authenticatedUser.email, 'secret123'); + vi.mocked(loginUser).mockResolvedValueOnce({ user }); + await useAppStore.getState().login(user.email, 'secret'); resolve(null); } else { vi.mocked(signOutUser).mockResolvedValueOnce(true); await useAppStore.getState().signOut(); - resolve(authenticatedUser); + resolve(user); } await restoration; - expect(useAppStore.getState().sessionStatus).toBe( - action === 'login' ? 'authenticated' : 'anonymous', - ); expect(useAppStore.getState().currentUser).toEqual( - action === 'login' ? authenticatedUser : null, - ); - expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBe( - action === 'login' ? 'new-token' : null, + action === 'login' ? user : null, ); }, ); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 11a1607..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, @@ -18,11 +17,8 @@ export type SessionStatus = | 'anonymous' | 'error'; -const SESSION_TOKEN_KEY = 'recipe-platform-session-token'; - -export const INITIAL_SAVED_RECIPE_IDS = recipes - .filter((recipe) => recipe.isSaved) - .map((recipe) => recipe.id); +// Remove credentials left by the old token-based client during migration. +const LEGACY_TOKEN_KEY = 'recipe-platform-session-token'; interface AppState { search: string; @@ -36,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 }), @@ -59,7 +45,7 @@ export const useAppStore = create((set) => ({ const result = await loginUser(email, password); authVersion += 1; - localStorage.setItem(SESSION_TOKEN_KEY, result.sessionToken); + localStorage.removeItem(LEGACY_TOKEN_KEY); set({ currentUser: result.user, @@ -71,7 +57,7 @@ export const useAppStore = create((set) => ({ const result = await registerUser(name, email, password); authVersion += 1; - localStorage.setItem(SESSION_TOKEN_KEY, result.sessionToken); + localStorage.removeItem(LEGACY_TOKEN_KEY); set({ currentUser: result.user, @@ -84,76 +70,26 @@ export const useAppStore = create((set) => ({ set({ currentUser: null, sessionStatus: 'restoring' }); try { - const sessionToken = localStorage.getItem(SESSION_TOKEN_KEY); - if (!sessionToken) { - set({ currentUser: null, sessionStatus: 'anonymous' }); - return; - } - - const currentUser = await getCurrentUser(sessionToken); + localStorage.removeItem(LEGACY_TOKEN_KEY); + const currentUser = await getCurrentUser(); if (version !== authVersion) return; - if (currentUser === null) { - localStorage.removeItem(SESSION_TOKEN_KEY); - } set({ currentUser, sessionStatus: currentUser ? 'authenticated' : 'anonymous', }); } catch { if (version !== authVersion) return; - // Keep the token for retry, but do not expose protected pages. + // The browser keeps the cookie for retry; protected pages remain hidden. set({ currentUser: null, sessionStatus: 'error' }); } }, signOut: async () => { - const sessionToken = localStorage.getItem(SESSION_TOKEN_KEY); + // Do not claim logout succeeded while the server session is still active. + await signOutUser(); authVersion += 1; - localStorage.removeItem(SESSION_TOKEN_KEY); + localStorage.removeItem(LEGACY_TOKEN_KEY); set({ currentUser: null, sessionStatus: 'anonymous' }); - if (sessionToken) { - await signOutUser(sessionToken); - } }, - - 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..814d033 --- /dev/null +++ b/apps/web/src/test/recipeApiFixtures.ts @@ -0,0 +1,59 @@ +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 }, + userRating: null, + 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..237fbe5 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; @@ -42,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 1b57e7e..eb3cdf7 100644 --- a/contracts/generated.ts +++ b/contracts/generated.ts @@ -8,69 +8,55 @@ export type Incremental = [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never; }; import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core'; -export type Maybe = T | null; -export type InputMaybe = Maybe; -/** All built-in and custom scalars, mapped to their actual values */ -export type Scalars = { - ID: { input: string; output: string }; - String: { input: string; output: string }; - Boolean: { input: boolean; output: boolean }; - Int: { input: number; output: number }; - Float: { input: number; output: number }; -}; - -export type User = { - __typename?: 'User'; - id: Scalars['ID']['output']; - name: Scalars['String']['output']; - email: Scalars['String']['output']; -}; - -export type AuthPayload = { - __typename?: 'AuthPayload'; - user: User; - sessionToken: Scalars['String']['output']; -}; +export type RecipeDifficulty = 'easy' | 'medium' | 'hard'; -export type Query = { - __typename?: 'Query'; - health: Scalars['String']['output']; - currentUser?: Maybe; -}; +export type RecipeVisibility = 'public' | 'private'; -export type QueryCurrentUserArgs = { - sessionToken: Scalars['String']['input']; -}; +export type RecipeCategory = + | 'breakfast' + | 'lunch' + | 'dinner' + | 'dessert' + | 'soup'; -export type Mutation = { - __typename?: 'Mutation'; - register: AuthPayload; - login: AuthPayload; - signOut: Scalars['Boolean']['output']; -}; +export type CookbookScope = 'all' | 'saved' | 'created'; -export type MutationRegisterArgs = { - name: Scalars['String']['input']; - email: Scalars['String']['input']; - password: Scalars['String']['input']; +export type RecipeListInput = { + search?: string | null | undefined; + category?: RecipeCategory | null | undefined; + maxCookingMinutes?: number | null | undefined; + page?: number | null | undefined; + pageSize?: number | null | undefined; }; -export type MutationLoginArgs = { - email: Scalars['String']['input']; - password: Scalars['String']['input']; +export type IngredientInput = { + name: string; + amount: number; + unit: string; + note?: string | null | undefined; }; -export type MutationSignOutArgs = { - sessionToken: Scalars['String']['input']; +export type RecipeInput = { + title: string; + description: string; + imageUrl?: string | null | undefined; + category: RecipeCategory; + cuisine?: string | null | undefined; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + prepMinutes: number; + cookMinutes: number; + servings: number; + ingredients: Array; + instructions: Array; + tags: Array; }; export type HealthQueryVariables = Exact<{ [key: string]: never }>; export type HealthQuery = { health: string }; -export type SignOutMutationVariables = Exact<{ - sessionToken: string; -}>; +export type SignOutMutationVariables = Exact<{ [key: string]: never }>; export type SignOutMutation = { signOut: boolean }; @@ -81,10 +67,7 @@ export type RegisterMutationVariables = Exact<{ }>; export type RegisterMutation = { - register: { - sessionToken: string; - user: { id: string; name: string; email: string }; - }; + register: { user: { id: string; name: string; email: string } }; }; export type LoginMutationVariables = Exact<{ @@ -93,20 +76,433 @@ export type LoginMutationVariables = Exact<{ }>; export type LoginMutation = { - login: { - sessionToken: string; - user: { id: string; name: string; email: string }; - }; + login: { user: { id: string; name: string; email: string } }; }; -export type CurrentUserQueryVariables = Exact<{ - sessionToken: string; -}>; +export type CurrentUserQueryVariables = Exact<{ [key: string]: never }>; export type CurrentUserQuery = { currentUser: { id: string; name: string; email: string } | null; }; +export type RecipeFieldsFragment = { + 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 RecipesQueryVariables = Exact<{ + input?: RecipeListInput | null | undefined; +}>; + +export type RecipesQuery = { + recipes: { + totalCount: number; + totalPages: number; + page: number; + pageSize: number; + items: Array<{ + 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 RecipeQueryVariables = Exact<{ + id: string | number; +}>; + +export type RecipeQuery = { + recipe: { + 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 }; + } | null; +}; + +export type CookbookQueryVariables = Exact<{ + input?: RecipeListInput | null | undefined; + scope?: CookbookScope | null | undefined; +}>; + +export type CookbookQuery = { + cookbook: { + totalCount: number; + totalPages: number; + page: number; + pageSize: number; + items: Array<{ + 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 CreateRecipeMutationVariables = Exact<{ + input: RecipeInput; +}>; + +export type CreateRecipeMutation = { + createRecipe: { + 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 UpdateRecipeMutationVariables = Exact<{ + id: string | number; + input: RecipeInput; +}>; + +export type UpdateRecipeMutation = { + updateRecipe: { + 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 DeleteRecipeMutationVariables = Exact<{ + id: string | number; +}>; + +export type DeleteRecipeMutation = { deleteRecipe: boolean }; + +export type SaveRecipeMutationVariables = Exact<{ + id: string | number; +}>; + +export type SaveRecipeMutation = { + saveRecipe: { + 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 UnsaveRecipeMutationVariables = Exact<{ + id: string | number; +}>; + +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: [ + { + 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 HealthDocument = { kind: 'Document', definitions: [ @@ -130,39 +526,10 @@ export const SignOutDocument = { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'SignOut' }, - variableDefinitions: [ - { - kind: 'VariableDefinition', - variable: { - kind: 'Variable', - name: { kind: 'Name', value: 'sessionToken' }, - }, - type: { - kind: 'NonNullType', - type: { - kind: 'NamedType', - name: { kind: 'Name', value: 'String' }, - }, - }, - }, - ], selectionSet: { kind: 'SelectionSet', selections: [ - { - kind: 'Field', - name: { kind: 'Name', value: 'signOut' }, - arguments: [ - { - kind: 'Argument', - name: { kind: 'Name', value: 'sessionToken' }, - value: { - kind: 'Variable', - name: { kind: 'Name', value: 'sessionToken' }, - }, - }, - ], - }, + { kind: 'Field', name: { kind: 'Name', value: 'signOut' } }, ], }, }, @@ -251,10 +618,6 @@ export const RegisterDocument = { selectionSet: { kind: 'SelectionSet', selections: [ - { - kind: 'Field', - name: { kind: 'Name', value: 'sessionToken' }, - }, { kind: 'Field', name: { kind: 'Name', value: 'user' }, @@ -339,10 +702,6 @@ export const LoginDocument = { selectionSet: { kind: 'SelectionSet', selections: [ - { - kind: 'Field', - name: { kind: 'Name', value: 'sessionToken' }, - }, { kind: 'Field', name: { kind: 'Name', value: 'user' }, @@ -370,19 +729,43 @@ export const CurrentUserDocument = { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'CurrentUser' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'currentUser' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'email' } }, + ], + }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; +export const RecipesDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'query', + name: { kind: 'Name', value: 'Recipes' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', - name: { kind: 'Name', value: 'sessionToken' }, + name: { kind: 'Name', value: 'input' }, }, type: { - kind: 'NonNullType', - type: { - kind: 'NamedType', - name: { kind: 'Name', value: 'String' }, - }, + kind: 'NamedType', + name: { kind: 'Name', value: 'RecipeListInput' }, }, }, ], @@ -391,28 +774,1118 @@ export const CurrentUserDocument = { selections: [ { kind: 'Field', - name: { kind: 'Name', value: 'currentUser' }, + name: { kind: 'Name', value: 'recipes' }, arguments: [ { kind: 'Argument', - name: { kind: 'Name', value: 'sessionToken' }, + name: { kind: 'Name', value: 'input' }, value: { kind: 'Variable', - name: { kind: 'Name', value: 'sessionToken' }, + name: { kind: 'Name', value: 'input' }, }, }, ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'items' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'totalCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'totalPages' } }, + { kind: 'Field', name: { kind: 'Name', value: 'page' } }, + { kind: 'Field', name: { kind: 'Name', value: 'pageSize' } }, + ], + }, + }, + ], + }, + }, + { + 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: 'email' } }, ], }, }, + { + 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; +} as unknown as DocumentNode; +export const RecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'query', + name: { kind: 'Name', value: 'Recipe' }, + 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: 'recipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + 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 CookbookDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'query', + name: { kind: 'Name', value: 'Cookbook' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'RecipeListInput' }, + }, + }, + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'scope' }, + }, + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'CookbookScope' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'cookbook' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'input' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + }, + { + kind: 'Argument', + name: { kind: 'Name', value: 'scope' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'scope' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'items' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'totalCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'totalPages' } }, + { kind: 'Field', name: { kind: 'Name', value: 'page' } }, + { kind: 'Field', name: { kind: 'Name', value: 'pageSize' } }, + ], + }, + }, + ], + }, + }, + { + 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 CreateRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'CreateRecipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + type: { + kind: 'NonNullType', + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'RecipeInput' }, + }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'createRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'input' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + }, + ], + 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< + CreateRecipeMutation, + CreateRecipeMutationVariables +>; +export const UpdateRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'UpdateRecipe' }, + 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: 'input' }, + }, + type: { + kind: 'NonNullType', + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'RecipeInput' }, + }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'updateRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + { + kind: 'Argument', + name: { kind: 'Name', value: 'input' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + }, + ], + 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< + UpdateRecipeMutation, + UpdateRecipeMutationVariables +>; +export const DeleteRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'DeleteRecipe' }, + 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: 'deleteRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + }, + ], + }, + }, + ], +} as unknown as DocumentNode< + DeleteRecipeMutation, + DeleteRecipeMutationVariables +>; +export const SaveRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'SaveRecipe' }, + 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: 'saveRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + 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 UnsaveRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'UnsaveRecipe' }, + 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: 'unsaveRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + }, + ], + }, + }, + ], +} as unknown as DocumentNode< + 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 83853e7..ebfb9a9 100644 --- a/contracts/operations.graphql +++ b/contracts/operations.graphql @@ -2,13 +2,12 @@ query Health { health } -mutation SignOut($sessionToken: String!) { - signOut(sessionToken: $sessionToken) +mutation SignOut { + signOut } mutation Register($name: String!, $email: String!, $password: String!) { register(name: $name, email: $email, password: $password) { - sessionToken user { id name @@ -19,7 +18,6 @@ mutation Register($name: String!, $email: String!, $password: String!) { mutation Login($email: String!, $password: String!) { login(email: $email, password: $password) { - sessionToken user { id name @@ -28,10 +26,109 @@ mutation Login($email: String!, $password: String!) { } } -query CurrentUser($sessionToken: String!) { - currentUser(sessionToken: $sessionToken) { +query CurrentUser { + currentUser { id name email } } + +fragment RecipeFields on Recipe { + id + title + description + category + cuisine + difficulty + visibility + imageUrl + sourceRecipeId + prepMinutes + cookMinutes + servings + createdAt + updatedAt + author { + id + name + } + ingredients { + id + name + amount + unit + note + } + instructions { + step + text + } + tags + rating { + average + count + } + userRating + saveCount + isSaved + isCreatedByCurrentUser +} +query Recipes($input: RecipeListInput) { + recipes(input: $input) { + items { + ...RecipeFields + } + totalCount + totalPages + page + pageSize + } +} +query Recipe($id: ID!) { + recipe(id: $id) { + ...RecipeFields + } +} +query Cookbook($input: RecipeListInput, $scope: CookbookScope) { + cookbook(input: $input, scope: $scope) { + items { + ...RecipeFields + } + totalCount + totalPages + page + pageSize + } +} +mutation CreateRecipe($input: RecipeInput!) { + createRecipe(input: $input) { + ...RecipeFields + } +} +mutation UpdateRecipe($id: ID!, $input: RecipeInput!) { + updateRecipe(id: $id, input: $input) { + ...RecipeFields + } +} +mutation DeleteRecipe($id: ID!) { + deleteRecipe(id: $id) +} +mutation SaveRecipe($id: ID!) { + saveRecipe(id: $id) { + ...RecipeFields + } +} +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/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..65c7e1a --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,58 @@ +# Arkitektur og prosjektstruktur + +React-klienten bruker en felles, typet GraphQL-klient. GraphQL Yoga validerer +forespørsler og kaller tjenester og repositories. PostgreSQL lagrer dataene. +Eierskap og synlighet kontrolleres i API-et; skjulte knapper er ikke tilgangskontroll. + +| Mappe | Ansvar | +| --------------------- | --------------------------------------------------------------- | +| `apps/web` | React, sider, komponenter, URL-state og klientens API-kall | +| `apps/api` | GraphQL-skjema, resolvere, autentisering og databaseoperasjoner | +| `apps/api/src/db` | Drizzle-skjema, databasekobling, migreringskode og seed | +| `apps/api/migrations` | Versjonerte SQL-migrasjoner og Drizzle-metadata | +| `apps/validation` | Delt Zod-validering for autentisering | +| `contracts` | Klientens GraphQL-operasjoner og genererte operasjonstyper | +| `scripts` | Typegenerering, integrasjonstester, bildeopprydding og deploy | +| `e2e` | Playwright-tester av brukerflyter | +| `docs` | Detaljert dokumentasjon og historikk | + +## Hvorfor to genererte filer? + +Begge bygger på `apps/api/src/schema.graphql`, men har ulike mottakere: + +- `apps/api/src/generated.ts` inneholder serverens skjema- og resolvertyper. +- `contracts/generated.ts` inneholder klienttyper og typede dokumenter for + operasjonene i `contracts/operations.graphql`. + +Kjør `npm run types:api` etter endringer i skjema eller operasjoner. Filene skal +ikke redigeres manuelt. `npm run types:check` kontrollerer at de er oppdaterte. +`apps/validation` inneholder kjørbar validering, mens `contracts` beskriver +GraphQL-kommunikasjonen. De har derfor ulike oppgaver. + +## PostgreSQL, Drizzle og SQL + +PostgreSQL passer til relasjonene mellom brukere, oppskrifter, ingredienser, +vurderinger og lagrede oppskrifter. Fremmednøkler, unike nøkler og sjekkregler +beskytter dataintegriteten. + +Drizzle beskriver databaseskjemaet og brukes til å generere og kontrollere +migrasjoner. Repositories bruker parameterisert SQL gjennom `pg`, med eksplisitte +transaksjoner for operasjoner som skriver flere relaterte rader. Prosjektet bruker +dermed ikke Drizzle som spørringsbygger i repositories. SQL-valget gir direkte +kontroll over tilgangsvilkår, aggregater og transaksjoner, men krever at SQL og +resultattyper vedlikeholdes og testes. + +Søk og filtre utføres før `LIMIT`/`OFFSET`. Det finnes indekser for blant annet +forfatter, offentlige oppskrifters opprettingstid og relasjoner. Et stort datasett +og målinger av spørringsplaner trengs før vi kan hevde at løsningen skalerer godt. + +## Klientens dataflyt + +`apps/web/src/lib/graphqlClient.ts` håndterer GraphQL-transporten. +Oppskriftsfunksjonene bruker `recipeApi.ts` og `useRecipeQuery.ts` for lesing, +avbryting av utdaterte forespørsler og oppfrisking etter mutations. URL-en beholder +søk, filtre og sidetall. En separat caching-avhengighet er ikke innført; +dagens avgrensede flyt testes med kontrollerte API-svar og integrasjonstester. + +Tidligere mockdata brukes ikke som applikasjonens datakilde. Historiske +prototypebeskrivelser ligger i [leveransehistorikken](delivery-history.md). diff --git a/docs/auth-improvements.md b/docs/auth-improvements.md index 2b053d4..2534f9b 100644 --- a/docs/auth-improvements.md +++ b/docs/auth-improvements.md @@ -1,6 +1,7 @@ # Auth-forbedringer -Dette er en avgrenset auth-endring. CRUD-arbeid og cookie-overgang er egne steg. +Dette er en avgrenset auth-endring. Cookie/context-migreringen er inkludert; +CRUD-arbeid er et eget steg. ## Delt validering @@ -14,8 +15,9 @@ Backend validerer alltid på nytt, uavhengig av hva klienten sender. - Registreringspassord er 6–128 tegn. Passord trimmes aldri. - Login krever et ikke-tomt passord, uten registreringens lengdekrav. Bekreftelsesfeltet finnes bare i frontendens registreringsskjema. -- Sesjons-ID må være en UUID før databaseoppslag eller logout-sletting. - Ugyldig ID gir `null` fra currentUser og `false` fra signOut. +- Sesjons-ID i cookien må være en UUID før databaseoppslag eller logout-sletting. + Ugyldig cookie gir `null` fra currentUser og slettes. SignOut er idempotent: + også en allerede utlogget bruker får `true` og en slettet cookie. - Sesjonsoppslag krever fortsatt `expires_at > now()`. ## Feilkoder og klientkontrakt @@ -28,8 +30,14 @@ fra backend. Uventede feil og HTML/ugyldig JSON gir en generell feilmelding. Auth-klienten bruker de genererte Register, Login, CurrentUser og SignOut- dokumentene fra `contracts/generated.ts`. Endre operasjonene i `contracts/operations.graphql` og kjør `npm run types:api` ved kontraktendringer. -Eksisterende tokenargumenter, localStorage, sesjonsgjenoppretting og beskyttede -ruter beholdes. Ingen databasemigrasjon er nødvendig. +AuthPayload returnerer bare brukerdata. `currentUser` og `signOut` har ingen +tokenargumenter. Backend setter en host-only cookie med HttpOnly, SameSite=Lax, +Path=/ og Max-Age=604800. GraphQL-context validerer cookien og henter brukeren +fra en ikke-utløpt sesjon. Ugyldig/utløpt cookie slettes; databasefeil beholder +cookien for retry. Logout tilbakekaller sesjonen før cookien slettes med samme +Path og Max-Age=0. Klienten rydder gamle localStorage-tokens og sender +`credentials: same-origin`. Eksisterende brukere må logge inn igjen. +Ingen databasemigrasjon er nødvendig. ## Enkel rate limiting @@ -68,10 +76,22 @@ rate-limit-vindu og proxy-headerhåndtering. GraphQL-testene kjører det faktisk Yoga-endepunktet med et kontrollert repository; de bruker ikke live-databasen. Frontendtestene dekker sesjonsgjenoppretting og beskyttede ruter. -HttpOnly-cookie og HTTPS gjenstår. Token i localStorage kan leses av JavaScript -på samme origin. Denne endringen fjerner ikke XSS- eller HTTP-transport-risikoen. -Det må verifiseres på VM at Apache videresender klient-IP som forventet og at -login/register/refresh/logout fungerer etter deploy. +HTTPS gjenstår. Sett `AUTH_COOKIE_SECURE=true` når HTTPS er konfigurert; behold +false for localhost og dagens NTNU HTTP-oppsett. Flagget bygger ikke på en +klientstyrt X-Forwarded-Proto-header. HttpOnly hindrer direkte lesing av cookien, +men XSS kan fortsatt utføre handlinger fra samme origin. HTTP beskytter ikke +passord eller token under overføring. + +POST krever application/json og `X-Requested-With: recipe-platform`. +`cors: false` hindrer cross-origin preflight, og en HTML-form kan ikke sette +den påkrevde headeren. GraphiQL bruker samme header. Yoga avviser GET-mutasjoner. +`Cache-Control: no-store` hindrer caching av brukeravhengige responser. + +Cookie-testene dekker login/register, context-restoration, logout, ugyldige og +utløpte sesjoner, HttpOnly/SameSite/Path/Max-Age/Secure og avvist enkel POST. +Nettlesertesten bruker ekte Yoga HTTP/cookies med en kontrollert auth-service +og sjekker document.cookie, refresh og logout. Etter deploy må samme flyt og +Apaches klient-IP-videresending verifiseres på VM. AI er brukt til implementasjon, testutforming og gjennomgang. Endringene skal vurderes i PR før sammenslåing. diff --git a/docs/delivery-history.md b/docs/delivery-history.md new file mode 100644 index 0000000..7aa8eb0 --- /dev/null +++ b/docs/delivery-history.md @@ -0,0 +1,58 @@ +# Historikk fra tidligere leveranser + +Dette dokumentet beskriver tidligere milepæler, ikke dagens funksjonalitet. Se [README](../README.md) for gjeldende status. + +## Første underveislevering + +Første leveranse skal gjøre konseptet forståelig gjennom en sammenhengende prototype. Følgende skal kunne demonstreres med lokale mockdata: + +- Explore med oppskriftskort +- søk, filtrering, sortering og paginering +- Recipe Detail med ingredienser og nummererte steg +- My Cookbook med **All**, **Saved** og **Created by me** +- mock Save to Cookbook +- Add Recipe med validering og repeterbare ingrediens-/instruksjonsfelt +- Login, Register og Sign out med en felles mockbruker i state +- responsive skjermbilder for mobil og desktop +- tydelige tomme tilstander, feil, lasting og bekreftelser + +### Mocking og avgrensninger + +I første leveranse: + +- kommer oppskriftene fra et delt, statisk TypeScript-datasett +- behandles søk, filtrering, sortering og paginering lokalt +- er innlogging og registrering mocket uten ekte passordkontroll +- lagres ikke brukerdata eller nye oppskrifter permanent i databasen +- utføres ingen tester mot en ekstern nettverkstjeneste + +Mockdata ligger adskilt fra komponentene og bruker delte TypeScript-modeller. Dette gjør det mulig å erstatte den lokale datakilden med GraphQL uten å redesigne hele frontendstrukturen. + +## Andre underveislevering + +Etter første underveislevering 2. oktober har vi videreutviklet frontend, +autentisering og databasegrunnlaget. Oversikten beskriver arbeidet som er flettet +inn i `dev` til og med 16. oktober 2026, commit `48e925b`. + +### Utviklet siden første underveislevering + +| Område | Hva som er utviklet | PR | +| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | +| Explore | Responsive filtre og sortering. Søk, filtre og sidetall beholdes i URL-en ved oppdatering og navigering. | [#31](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/31) | +| Add Recipe | Skjema med validering, bildeforhåndsvisning, drag-and-drop og redigerbare ingredienser og instruksjoner. | [#40](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/40) | +| Forbedret opprettingsskjema | Separate ingrediensfelt for navn, mengde og enhet, bildebeskjæring og forbedret omorganisering av ingredienser og steg. | [#52](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/52) | +| My Cookbook | Visninger for lagrede og egne oppskrifter, med søk, filtrering, sortering og paginering. | [#43](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/43) | +| Oppskriftsdetaljer | Detaljside med bilde, forfatter, tilberedningsinformasjon, ingredienser og instruksjoner. Justerbare porsjoner med skalering av mengder, lagrings- og vurderingsinteraksjoner og tilbakegang til tidligere søk og filtre. | [#46](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/46) | +| Navigasjon | Refaktorert header med felles logo- og lenkekomponenter og tilpasning til ulike skjermstørrelser. | [#45](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/45) | +| Autentisering | Registrering, innlogging, utlogging og vedvarende sesjoner med PostgreSQL og passordhashing. Beskyttede ruter venter på sesjonsgjenoppretting før eventuell videresending til login. | [#41](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/41) | +| Auth-forbedringer | Delte Zod-skjemaer, validering av sesjons-ID, strukturerte feilkoder, genererte GraphQL-operasjoner og enkel rate limiting for login og registrering. | [#53](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/53) | +| Databasemodell | Relasjoner for oppskrifter, forfattere, ingredienser, instruksjoner, tagger, bokmerker og vurderinger. Migrasjoner, indekser og datavalidering, valgfritt cuisine-felt, faste kategorier og kildehenvisning for oppskriftskopier. | [#47](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/47) | + +I tillegg er følgende gjennomført: + +- **Feilhåndtering:** Egen 404-side og separat håndtering av ukjente oppskrifts-ID-er. +- **Lokalt utviklingsmiljø:** Docker-oppsett for frontend, API og PostgreSQL, med + oppdatert dokumentasjon for installasjon og oppstart. +- **Testing og dokumentasjon:** Utvidede frontend-, backend-, database- og + nettlesertester. Dokumentasjon av databasemodellen, autentisering og videre + serverintegrasjon. diff --git a/docs/frontend-integration.md b/docs/frontend-integration.md new file mode 100644 index 0000000..d446312 --- /dev/null +++ b/docs/frontend-integration.md @@ -0,0 +1,81 @@ +# 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] 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. + +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 +`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. +- [ ] 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. Obsolete prototype query modules and their tests +have been removed. + +## 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. 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 +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 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/operations.md b/docs/operations.md new file mode 100644 index 0000000..dcc11fb --- /dev/null +++ b/docs/operations.md @@ -0,0 +1,92 @@ +# Drift og testing + +Se [README](../README.md) for lokal oppstart med og uten Docker. Docker brukes +til lokal utvikling. På VM-en kjører PostgreSQL og API-tjenesten direkte på verten, +med Apache foran API-et og den bygde klienten. + +## Versjoner og miljø + +Bruk Node 24.x og npm 11.x. `.nvmrc`, `.node-version` og `Dockerfile.dev` angir +referanseversjonen 24.21.0. Bruk `nvm install` og `nvm use` der nvm er tilgjengelig. + +Lokalt kopieres `.env.example` til `.env`. På VM-en leser deploy-migrasjonen +`/etc/t31-project2.env`. Hemmeligheter skal ikke lagres i Git. + +| Variabel | Bruk | +| ---------------------- | --------------------------------------------------------------- | +| `DATABASE_URL` | PostgreSQL-tilkoblingen for det aktuelle miljøet | +| `API_HOST`, `API_PORT` | API-ets lytteadresse; normalt `127.0.0.1:3001` på VM | +| `AUTH_TRUST_PROXY` | Aktiveres bare bak det dokumenterte lokale Apache-oppsettet | +| `AUTH_COOKIE_SECURE` | `true` ved HTTPS; `false` i dagens HTTP-oppsett | +| `UPLOAD_DIR` | Absolutt, vedvarende bildemappe som API-brukeren kan skrive til | + +Sett `UPLOAD_DIR` utenfor release-mappene på VM-en, slik at opplastede bilder +beholdes ved deploy. Apache må videresende `/project2/api/graphql` til `/graphql` +og `/project2/api/uploads` til `/uploads` på API-et. Klienten publiseres under +`/project2/`. Eksakt Apache- og systemd-konfigurasjon administreres på VM-en og +ligger ikke i dette repositoryet. + +## Tester før PR + +```bash +npm ci +npm run check +npm run test:db +npm run test:api +npx playwright install chromium +npm run test:e2e +``` + +Database- og API-testene krever `DATABASE_URL` til en utviklings-/testdatabase og +CREATE SCHEMA-rettighet. De bruker isolerte skjemaer; API- og nettlesertestene +bruker midlertidige bildefiler. Bruk ikke produksjonsdatabasen. +Nettlesertesten for oppskrifter hoppes over lokalt dersom `DATABASE_URL` mangler. + +## CI uten Docker + +Den self-hosted CI-runneren trenger tilgang til en separat PostgreSQL-testdatabase. +En administrator oppretter testbruker og testdatabase én gang. Testbrukeren må +kunne opprette skjemaer i testdatabasen; den trenger ikke produksjonstilgang. + +Legg til repository-secret `TEST_DATABASE_URL` under +**Settings → Secrets and variables → Actions**, for eksempel: + +```text +postgresql://TEST_USER:URL_ENCODED_PASSWORD@TEST_HOST:5432/project2_test +``` + +`127.0.0.1` brukes bare når PostgreSQL og runneren kjører på samme vert. +Workflowen setter `DATABASE_URL` fra hemmeligheten og feiler tydelig hvis den +mangler. Den kjører `check`, `test:db`, `test:api` og Playwright. + +## Migrasjoner og utrulling på VM + +PR-er kjører kvalitetssjekkene. Push til `main` kjører i tillegg deploy etter +bestått `quality`. Workflowen: + +1. Pakker de testede byggene og migrasjonene som et release-artifact. +2. Installerer produksjonsavhengigheter på deploy-runneren. +3. Kjører migrasjoner med `/etc/t31-project2.env`. +4. Kaller `scripts/deploy.sh`, som oppretter en release under + `/srv/t31-project2/releases`, oppdaterer `current` og restarter + `t31-project2-api` med systemd. +5. Kontrollerer API-ets health-query på `127.0.0.1:3001`. + +Ved manuell klargjøring kan migrasjoner kjøres fra release-mappen med: + +```bash +node --env-file=/etc/t31-project2.env apps/api/dist/db/migrate.js +``` + +Etter deploy kontrolleres innlogging, oppskrifter, bildeopplasting og persistens +ved oppdatering av siden. Se [review-testguiden](review-test-guide.md). + +For feilsøking på VM: + +```bash +systemctl status t31-project2-api +sudo journalctl -u t31-project2-api -n 100 --no-pager +``` + +Ikke del logger som inneholder hemmeligheter. Bildeopprydding kjøres ved API-start +og hver time; refererte bilder beholdes, og urefererte bilder beholdes i 24 timer. diff --git a/docs/recipe-api.md b/docs/recipe-api.md new file mode 100644 index 0000000..b6dbfb1 --- /dev/null +++ b/docs/recipe-api.md @@ -0,0 +1,258 @@ +# Recipe API – Delivery 2 + +API-et bruker eksisterende GraphQL Yoga og +PostgreSQL-oppsett, med SQL-parametre gjennom `pg`, som autentiseringen. +Zod validerer input; databasekontrollene beholdes. Bildeopplastingen bruker nå en egen migrasjon for filmetadata. + +## Hurtigstart for frontend + +Alle queries og mutations sendes med HTTP POST til samme GraphQL-adresse. +Operasjonsnavnet i forespørselen bestemmer hva serveren gjør. + +| Miljø | Adresse fra frontend | +| ----------------- | --------------------------------------------------- | +| Lokal Vite-server | `/graphql` (Vite videresender til API på port 3001) | +| Deploy på VM | `/project2/api/graphql` | + +Start lokalt med `npm run dev` fra prosjektroten. PostgreSQL må kjøre, +`DATABASE_URL` må være satt i `.env`, og migrasjonene må være kjørt med +`npm run db:migrate`. + +Bruk de ferdige operasjonene i [operations.graphql](../contracts/operations.graphql) +og importer tilhørende dokumenter og typer fra +[generated.ts](../contracts/generated.ts). Ikke rediger den genererte filen. + +| Komponent/funksjon | Generert dokument | +| ------------------ | --------------------------------------------- | +| Explore | `RecipesDocument` | +| Recipe Detail | `RecipeDocument` | +| Add Recipe | `CreateRecipeDocument` | +| Edit Recipe | `UpdateRecipeDocument` | +| Slett oppskrift | `DeleteRecipeDocument` | +| Save / Unsave | `SaveRecipeDocument` / `UnsaveRecipeDocument` | +| Cookbook | `CookbookDocument` | + +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 +import { print } from 'graphql'; +import { + CreateRecipeDocument, + type CreateRecipeMutation, + type CreateRecipeMutationVariables, +} from '../../../../../contracts/generated'; + +export async function createRecipe( + input: CreateRecipeMutationVariables['input'], +) { + const url = import.meta.env.DEV ? '/graphql' : '/project2/api/graphql'; + const variables: CreateRecipeMutationVariables = { input }; + const response = await fetch(url, { + method: 'POST', + credentials: 'same-origin', + headers: { + 'Content-Type': 'application/json', + 'X-Requested-With': 'recipe-platform', + }, + body: JSON.stringify({ query: print(CreateRecipeDocument), variables }), + }); + if (!response.ok) throw new Error('Kunne ikke kontakte API-et.'); + + const result = (await response.json()) as { + data?: CreateRecipeMutation; + errors?: Array<{ message: string; extensions?: { code?: string } }>; + }; + const error = result.errors?.[0]; + if (error) { + // Komponentlaget kan bruke koden til å velge en passende feilmelding. + throw new Error(error.extensions?.code ?? 'API_ERROR'); + } + if (!result.data) throw new Error('API-et returnerte ingen data.'); + return result.data.createRecipe; +} +``` + +Et gyldig `input` for eksempelet: + +```json +{ + "title": "Enkel suppe", + "description": "En rask suppe for to.", + "category": "soup", + "difficulty": "easy", + "visibility": "private", + "prepMinutes": 5, + "cookMinutes": 10, + "servings": 2, + "ingredients": [{ "name": "Vann", "amount": 1, "unit": "l" }], + "instructions": ["Kok opp vannet."], + "tags": ["quick"] +} +``` + +`updateRecipe` krever hele samme input, i tillegg til oppskriftens `id`; +operasjonen er ikke en delvis oppdatering. Listeoperasjoner returnerer +`items`, `totalCount`, `totalPages`, `page` og `pageSize`. Cookbook bruker +`scope: "all"`, `"saved"` eller `"created"`. + +Ved frontendkobling må komponenten håndtere lasting og feil, beholde formdata +ved feil og oppdatere relevante lister etter en vellykket mutation. +Explore, Cookbook, Detail og oppskriftsskjemaet bruker nå API-et. Se +[frontend integration checklist](frontend-integration.md). + +## Autentisering + +Branchen er oppdatert med `dev`, som inkluderer auth-cookie-forbedringene. Auth og CRUD bruker samme +GraphQL-context og HttpOnly-cookie. Serveren finner brukeren fra en gyldig, +ikke-utløpt sesjon. Forfatter og cookbook-bruker kommer alltid fra context, +aldri fra klientens bruker-ID. `currentUser` returnerer bruker eller `null`. + +Frontend sender `credentials: 'same-origin'`, `Content-Type: application/json` +og `X-Requested-With: recipe-platform`, som eksisterende auth-klient. +Sesjonstoken sendes ikke som GraphQL-argument eller i responsdata, og lagres +ikke i localStorage. Logout sletter cookien og ugyldiggjør sesjonen i databasen. +Cookie har HttpOnly, SameSite=Lax og Path=/; Secure aktiveres ved HTTPS. + +## Operasjoner + +Alle operasjonene finnes i `contracts/operations.graphql`, med genererte typer og +dokumenter i `contracts/generated.ts`. Regenerer med `npm run types:api`. + +| Operasjon | Tilgang og oppførsel | +| ------------------------- | ----------------------------------------------------------------------------- | +| `recipes(input)` | Offentlige oppskrifter, også for innlogget eier. | +| `recipe(id)` | Offentlig oppskrift eller eierens private. Utilgjengelig/ukjent gir `null`. | +| `createRecipe(input)` | Krever innlogging; lagrer hele oppskriften i én transaksjon. | +| `updateRecipe(id, input)` | Bare eier; erstatter alle redigerbare felt og barn i én transaksjon. | +| `deleteRecipe(id)` | Bare eier; databasen sletter tilknyttede rader automatisk. | +| `saveRecipe(id)` | Bare innlogget bruker; offentlig oppskrift av en annen bruker; idempotent. | +| `unsaveRecipe(id)` | Fjerner bare egen lagring; idempotent, også etter at oppskriften blir privat. | +| `cookbook(input, scope)` | Krever innlogging. Scope er `all`, `saved` eller `created`. | + +Listeinput støtter `search` (tittel/beskrivelse), `category`, `maxCookingMinutes`, +`page` og `pageSize` (1–50, standard 6). Filtrering og paginering skjer i SQL. +Sortering er nyeste først med ID som stabil tie-breaker. En side utenfor området +begrenses til siste side. Tom liste har `totalPages: 0` og `page: 1`. + +Oppskriften returnerer forfatterens offentlige ID/navn, ingredienser, ordnede steg, +tagger, datoer, vurderingsoppsummering og brukeravhengige lagrings-/eierskapsflagg. +E-post og passordhash eksponeres ikke som oppskriftsforfatterdata. + +## Input og frontendkobling + +`RecipeInput` inneholder tittel, beskrivelse, kategori, difficulty, visibility, +prepMinutes, cookMinutes, servings, ingredients, instructions og tags. +`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 +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 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. Skjemaet har eksplisitte felt for difficulty, + prepMinutes og cookMinutes; ikke gjett vanskelighetsgrad + eller fordel den eksisterende cookingTime-verdien automatisk. +- 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. +- Bruk eksisterende pending/error/not-found-mønstre og behold formdata ved feil. + +Feilkoder: `BAD_USER_INPUT`, `UNAUTHENTICATED`, `NOT_FOUND` og `FORBIDDEN`. +Ugyldige enumverdier avvises av GraphQL før resolveren kjøres; klienten må også +håndtere GraphQL-valideringsfeil uten disse domenekodene. +Uventede databasefeil maskeres av Yoga. Oppdatering/sletting av andres eller +ukjente oppskrifter gir samme feil og avslører ikke private data. + +### Avtale for frontendintegrasjon og videre arbeid + +- GraphQL bruker RecipeDifficulty, RecipeVisibility, RecipeCategory og + CookbookScope som enums. Verdiene beholder databasens små bokstaver, for + eksempel `easy`, `public`, `soup` og `saved`. JSON-variabler sendes fortsatt + som strenger, men inline enumverdier skrives uten anførselstegn. Cookbook- + operasjoner må deklarere `$scope: CookbookScope`, ikke `$scope: String`. + 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. 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. +- 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. +- 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. 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. + Listeoperasjonene henter foreløpig komplette oppskrifter også i databasen. + +## Lokal kontroll og seed + +Kjør fra roten, med `DATABASE_URL` i `.env`: + +```powershell +npm.cmd run db:migrate +npm.cmd run check +npm.cmd run test:db +npm.cmd run test:api +``` + +`test:api` kjører virkelige GraphQL-operasjoner mot et tilfeldig PostgreSQL-skjema. +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. +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: + +```powershell +$env:SEED_PASSWORD = '' +npm.cmd run db:seed +Remove-Item Env:SEED_PASSWORD +``` + +Seed oppretter `demo@example.invalid`, én offentlig og én privat suppe med faste +UUID-er og strukturerte barn i én transaksjon. Gjentatte kjøringer overskriver +ikke eksisterende seed-rader eller passord. Kjøres eksplisitt, aldri under deploy. +Passordet lagres som Argon2-hash. På Linux: `SEED_PASSWORD='...' npm run db:seed`. + +## Sjekk mot Delivery 2-planen + +- D2-01/03: relasjoner og migrasjoner finnes allerede; kontrakter er utvidet. +- D2-04: eksplisitt demoseed er lagt til. +- 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: 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 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 +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/auth-cookie.spec.ts b/e2e/auth-cookie.spec.ts new file mode 100644 index 0000000..b25bffc --- /dev/null +++ b/e2e/auth-cookie.spec.ts @@ -0,0 +1,104 @@ +import { createServer, type Server } from 'node:http'; +import { randomUUID } from 'node:crypto'; +import { expect, test } from '@playwright/test'; +import { createApp } from '../apps/api/src/app.js'; +import type { AuthService } from '../apps/api/src/features/auth/authService.js'; + +let server: Server; +let endpoint: string; +const sessions = new Set(); +const user = { + id: '22222222-2222-4222-8222-222222222222', + name: 'Cookie User', + email: 'cookie@example.com', +}; +test.beforeAll(async () => { + const login = async () => { + const sessionToken = randomUUID(); + sessions.add(sessionToken); + return { user, sessionToken }; + }; + const service: AuthService = { + login, + register: login, + currentUser: async (token) => (sessions.has(token) ? user : null), + signOut: async (token) => sessions.delete(token), + }; + server = createServer(createApp(service, false, false)); + 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())), + ); +}); +test('login uses an HttpOnly cookie, survives refresh and revokes logout', async ({ + page, + context, +}) => { + // 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 }); + }); + await page.goto('cookbook'); + await expect(page).toHaveURL(/\/login$/); + await page.getByLabel(/^Email/).fill(user.email); + await page.getByLabel(/^Password/).fill('secret123'); + await page.getByRole('button', { name: 'Log in', exact: true }).click(); + await expect( + page.getByRole('heading', { name: 'My Cookbook' }), + ).toBeVisible(); + const cookie = (await context.cookies()).find( + (cookie) => cookie.name === 't31_project2_session', + ); + expect(cookie).toBeDefined(); + expect(cookie?.httpOnly).toBe(true); + expect(cookie?.sameSite).toBe('Lax'); + expect(cookie?.path).toBe('/'); + expect(await page.evaluate(() => document.cookie)).not.toContain( + 't31_project2_session', + ); + expect( + await page.evaluate(() => + localStorage.getItem('recipe-platform-session-token'), + ), + ).toBeNull(); + await page.reload(); + await expect( + page.getByRole('heading', { name: 'My Cookbook' }), + ).toBeVisible(); + await page.getByRole('button', { name: 'Sign out' }).click(); + await expect + .poll(async () => + (await context.cookies()).some( + (cookie) => cookie.name === 't31_project2_session', + ), + ) + .toBe(false); + expect(sessions.has(cookie!.value)).toBe(false); + await page.goto('cookbook'); + await expect(page).toHaveURL(/\/login$/); +}); diff --git a/e2e/recipe-api.spec.ts b/e2e/recipe-api.spec.ts new file mode 100644 index 0000000..b0b3268 --- /dev/null +++ b/e2e/recipe-api.spec.ts @@ -0,0 +1,239 @@ +import { createServer, type Server } from 'node:http'; +import { randomUUID } from 'node:crypto'; +import { existsSync } from 'node:fs'; +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'; +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; +let imageDirectory: string; + +test.beforeAll(async () => { + imageDirectory = await mkdtemp(join(tmpdir(), 'recipe-browser-images-')); + 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 }, + imageDirectory, + ), + ); + 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(); + } + 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 }); + }); +} +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 recipes, uploaded images and ratings 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.'); + 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' }), + ).toBeVisible(); + const recipeUrl = page.url(); + await page.reload(); + 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(); + 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: '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(); + 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 }), + ).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.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' }), + ).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 2a6e477..1f29c64 100644 --- a/e2e/smoke.spec.ts +++ b/e2e/smoke.spec.ts @@ -1,8 +1,67 @@ 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 }, + userRating: null, + 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; + variables?: { id?: string }; + }; + if (body.query?.includes('currentUser')) { + await route.fulfill({ json: { data: { currentUser: null } } }); + } 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'], diff --git a/package-lock.json b/package-lock.json index de8db14..60476a7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -37,8 +37,8 @@ "vitest": "4.0.14" }, "engines": { - "node": ">=22", - "npm": ">=10" + "node": "24.x", + "npm": "11.x" } }, "apps/api": { diff --git a/package.json b/package.json index 773ce73..09c0afc 100644 --- a/package.json +++ b/package.json @@ -6,8 +6,8 @@ "apps/*" ], "engines": { - "node": ">=22", - "npm": ">=10" + "node": "24.x", + "npm": "11.x" }, "scripts": { "predev": "npm run build --workspace @t31/validation", @@ -28,11 +28,14 @@ "lint": "eslint . --max-warnings 0", "format": "prettier --write .", "format:check": "prettier --check .", - "typecheck": "tsc -p apps/web/tsconfig.json && tsc -p apps/api/tsconfig.json --noEmit && tsc -p apps/api/tsconfig.test.json", + "typecheck": "tsc -p apps/web/tsconfig.json && tsc -p apps/api/tsconfig.json --noEmit && tsc -p apps/api/tsconfig.test.json && tsc -p scripts/tsconfig.json", "test": "vitest run --passWithNoTests", "test:e2e": "playwright test", "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: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", + "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/generate-api.ts b/scripts/generate-api.ts index 4584e61..0084dc0 100644 --- a/scripts/generate-api.ts +++ b/scripts/generate-api.ts @@ -15,12 +15,13 @@ const targets = [ { filename: 'apps/api/src/generated.ts', plugins: [{ typescript: {} }, { resolvers: {} }], - config: { useTypeImports: true }, + config: { useTypeImports: true, enumsAsTypes: true }, }, { filename: 'contracts/generated.ts', - plugins: [{ typescript: {} }, { operations: {} }, { typedDocument: {} }], - config: { useTypeImports: true }, + // typescript-operations v6 also emits the used input types. + plugins: [{ operations: {} }, { typedDocument: {} }], + config: { useTypeImports: true, enumsAsTypes: true }, }, ]; 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 new file mode 100644 index 0000000..766e2b7 --- /dev/null +++ b/scripts/test-recipe-api.ts @@ -0,0 +1,785 @@ +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +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'; +import type { TypedDocumentNode } from '@graphql-typed-document-node/core'; +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'; +import { seedDatabase } from '../apps/api/src/db/seedData.js'; +import { + RegisterDocument, + LoginDocument, + CurrentUserDocument, + SignOutDocument, + CreateRecipeDocument, + UpdateRecipeDocument, + DeleteRecipeDocument, + RecipesDocument, + RecipeDocument, + SaveRecipeDocument, + UnsaveRecipeDocument, + CookbookDocument, + RateRecipeDocument, + RemoveRecipeRatingDocument, + type RecipeInput, +} from '../contracts/generated.js'; + +await test('recipe GraphQL API against PostgreSQL', async (t) => { + assert.ok(process.env.DATABASE_URL, 'Set DATABASE_URL in .env.'); + const pool = new Pool({ + connectionString: process.env.DATABASE_URL, + 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', + description: 'Simple soup', + category: 'soup', + cuisine: null, + difficulty: 'easy', + visibility: 'public', + prepMinutes: 5, + cookMinutes: 10, + servings: 2, + ingredients: [ + { name: 'Salt', amount: 0.125, unit: 'tsp' }, + { name: 'Water', amount: 1, unit: 'l' }, + ], + instructions: ['Boil water', 'Add salt'], + tags: [' Quick ', 'quick'], + }; + async function request( + document: TypedDocumentNode, + variables: V, + cookie?: string, + ) { + const response = await api.fetch('http://localhost/graphql', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Requested-With': 'recipe-platform', + ...(cookie ? { Cookie: cookie } : {}), + }, + body: JSON.stringify({ query: print(document), variables }), + }); + const sessionCookie = + response.headers.get('set-cookie')?.split(';')[0] ?? ''; + const result = (await response.json()) as { + data: T; + errors?: { message: string; extensions: { code?: string } }[]; + }; + return { ...result, cookie: sessionCookie }; + } + async function ok( + document: TypedDocumentNode, + variables: V, + cookie?: string, + ) { + const result = await request(document, variables, cookie); + assert.equal(result.errors, undefined, JSON.stringify(result.errors)); + return result.data; + } + async function fails( + document: TypedDocumentNode, + variables: V, + code: string, + cookie?: string, + ) { + const result = await request(document, variables, cookie); + assert.equal( + result.errors?.[0]?.extensions.code, + code, + JSON.stringify(result), + ); + } + async function register(name: string, email: string) { + const result = await request(RegisterDocument, { + name, + email, + password: 'test-password', + }); + assert.equal(result.errors, undefined); + assert.ok(result.cookie); + assert.ok(!JSON.stringify(result.data).includes('sessionToken')); + return { ...result.data.register, cookie: result.cookie }; + } + async function loginSession(email: string, password: string) { + const result = await request(LoginDocument, { email, password }); + assert.equal(result.errors, undefined); + assert.ok(result.cookie); + return { ...result.data.login, cookie: result.cookie }; + } + try { + await pool.query(`CREATE SCHEMA "${schema}"`); + const journal = JSON.parse( + await readFile('apps/api/migrations/meta/_journal.json', 'utf8'), + ) as { entries: { tag: string }[] }; + // Exercise all real migrations; no writes to project2 or its migration history. + const client = await pool.connect(); + try { + await client.query('BEGIN'); + for (const { tag } of journal.entries) + await client.query( + (await readFile(`apps/api/migrations/${tag}.sql`, 'utf8')).replaceAll( + '"project2"', + `"${schema}"`, + ), + ); + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } finally { + client.release(); + } + + const owner = await register('Owner', 'owner@example.com'); + const reader = await register('Reader', 'reader@example.com'); + await t.test('persistent login and authenticated context', async () => { + const login = await loginSession('owner@example.com', 'test-password'); + assert.equal( + (await ok(CurrentUserDocument, {}, login.cookie)).currentUser?.id, + owner.user.id, + ); + assert.equal((await ok(CurrentUserDocument, {})).currentUser, null); + assert.equal( + ( + await ok( + CurrentUserDocument, + {}, + 't31_project2_session=invalid-token', + ) + ).currentUser, + null, + ); + await pool.query( + `UPDATE "${schema}".sessions SET expires_at=now()-interval '1 second' WHERE id=$1`, + [login.cookie.split('=')[1]], + ); + assert.equal( + (await ok(CurrentUserDocument, {}, login.cookie)).currentUser, + null, + ); + }); + await t.test( + 'anonymous, malformed and expired sessions cannot create', + async () => { + for (const token of [ + undefined, + 't31_project2_session=invalid-token', + 't31_project2_session=' + randomUUID(), + ]) + await fails( + CreateRecipeDocument, + { input }, + 'UNAUTHENTICATED', + token, + ); + }, + ); + await t.test('Zod rejects invalid input without writing rows', async () => { + for (const invalid of [ + { ...input, title: ' ' }, + { ...input, servings: 0 }, + { ...input, ingredients: [] }, + { ...input, instructions: [] }, + { + ...input, + ingredients: [{ name: 'Salt', amount: 0.00001, unit: 'tsp' }], + }, + ]) { + await fails( + CreateRecipeDocument, + { input: invalid }, + 'BAD_USER_INPUT', + owner.cookie, + ); + } + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".recipes`, + ) + ).rows[0].count, + 0, + ); + }); + const publicRecipe = ( + await ok(CreateRecipeDocument, { input }, owner.cookie) + ).createRecipe; + const privateRecipe = ( + await ok( + CreateRecipeDocument, + { input: { ...input, title: 'Private soup', visibility: 'private' } }, + 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 () => { + 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 () => { + assert.equal(publicRecipe.author.id, owner.user.id); + assert.equal(publicRecipe.cuisine, null); + assert.deepEqual(publicRecipe.tags, ['quick']); + const read = (await ok(RecipeDocument, { id: publicRecipe.id })) + .recipe!; + assert.equal(read.ingredients[0]?.amount, 0.125); + assert.deepEqual( + read.instructions.map((step) => step.text), + input.instructions, + ); + assert.equal(read.isCreatedByCurrentUser, false); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".recipes`, + ) + ).rows[0].count, + 2, + ); + }, + ); + await t.test( + 'public list excludes private data; private detail is owner-only', + async () => { + for (const token of [undefined, owner.cookie, reader.cookie]) { + const list = (await ok(RecipesDocument, {}, token)).recipes; + assert.deepEqual( + list.items.map((item) => item.id), + [publicRecipe.id], + ); + } + assert.equal( + (await ok(RecipeDocument, { id: privateRecipe.id })).recipe, + null, + ); + assert.equal( + (await ok(RecipeDocument, { id: privateRecipe.id }, reader.cookie)) + .recipe, + null, + ); + assert.equal( + (await ok(RecipeDocument, { id: privateRecipe.id }, owner.cookie)) + .recipe?.id, + privateRecipe.id, + ); + assert.equal( + (await ok(RecipeDocument, { id: randomUUID() })).recipe, + null, + ); + }, + ); + await t.test('search, filters and paging run on the server', async () => { + assert.equal( + ( + await ok(RecipesDocument, { + input: { search: 'SOUP', category: 'soup', page: 99, pageSize: 1 }, + }) + ).recipes.page, + 1, + ); + assert.equal( + (await ok(RecipesDocument, { input: { search: 'missing' } })).recipes + .totalCount, + 0, + ); + assert.equal( + (await ok(RecipesDocument, { input: { maxCookingMinutes: 14 } })) + .recipes.totalCount, + 0, + ); + await fails( + RecipesDocument, + { input: { pageSize: 51 } }, + 'BAD_USER_INPUT', + ); + }); + await t.test('only the owner can update or delete', async () => { + await fails( + UpdateRecipeDocument, + { id: publicRecipe.id, input }, + 'NOT_FOUND', + reader.cookie, + ); + await fails( + DeleteRecipeDocument, + { id: publicRecipe.id }, + 'NOT_FOUND', + reader.cookie, + ); + await fails( + UpdateRecipeDocument, + { id: publicRecipe.id, input }, + 'UNAUTHENTICATED', + ); + const edited = ( + await ok( + UpdateRecipeDocument, + { + id: publicRecipe.id, + input: { + ...input, + title: 'Updated soup', + instructions: ['Serve'], + ingredients: [{ name: 'Pepper', amount: 1, unit: '' }], + }, + }, + owner.cookie, + ) + ).updateRecipe; + assert.equal(edited.title, 'Updated soup'); + assert.equal(edited.ingredients.length, 1); + assert.deepEqual(edited.instructions, [{ step: 1, text: 'Serve' }]); + }); + await t.test( + 'save is idempotent, private recipes and own recipes are blocked', + async () => { + await fails( + SaveRecipeDocument, + { id: publicRecipe.id }, + 'UNAUTHENTICATED', + ); + await fails( + SaveRecipeDocument, + { id: privateRecipe.id }, + 'FORBIDDEN', + reader.cookie, + ); + await fails( + SaveRecipeDocument, + { id: publicRecipe.id }, + 'FORBIDDEN', + owner.cookie, + ); + for (let i = 0; i < 2; i++) { + const saved = ( + await ok(SaveRecipeDocument, { id: publicRecipe.id }, reader.cookie) + ).saveRecipe; + assert.equal(saved.isSaved, true); + assert.equal(saved.saveCount, 1); + } + assert.equal( + (await ok(CookbookDocument, { scope: 'saved' }, reader.cookie)) + .cookbook.totalCount, + 1, + ); + assert.equal( + (await ok(CookbookDocument, { scope: 'created' }, owner.cookie)) + .cookbook.totalCount, + 2, + ); + await fails(CookbookDocument, {}, 'UNAUTHENTICATED'); + }, + ); + await t.test( + 'making a saved recipe private hides it from other cookbooks', + async () => { + await ok( + UpdateRecipeDocument, + { id: publicRecipe.id, input: { ...input, visibility: 'private' } }, + owner.cookie, + ); + for (const scope of ['all', 'saved', 'created'] as const) { + assert.equal( + (await ok(CookbookDocument, { scope }, reader.cookie)).cookbook + .totalCount, + 0, + ); + } + assert.equal( + (await ok(RecipeDocument, { id: publicRecipe.id }, reader.cookie)) + .recipe, + null, + ); + await ok(UnsaveRecipeDocument, { id: publicRecipe.id }, reader.cookie); + await ok(UnsaveRecipeDocument, { id: publicRecipe.id }, reader.cookie); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".saved_recipes`, + ) + ).rows[0].count, + 0, + ); + }, + ); + await t.test( + 'child insert failures roll back both creation and updates', + async () => { + await pool.query( + `CREATE FUNCTION "${schema}".reject_test_ingredient() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.name='fail-test' THEN RAISE EXCEPTION 'forced child failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER reject_test BEFORE INSERT ON "${schema}".recipe_ingredients FOR EACH ROW EXECUTE FUNCTION "${schema}".reject_test_ingredient()`, + ); + const bad = { + ...input, + ingredients: [ + ...input.ingredients, + { name: 'fail-test', amount: 1, unit: '' }, + ], + }; + const failedCreate = await request( + CreateRecipeDocument, + { input: bad }, + owner.cookie, + ); + assert.ok(failedCreate.errors); + const before = ( + await ok(RecipeDocument, { id: privateRecipe.id }, owner.cookie) + ).recipe; + assert.ok( + ( + await request( + UpdateRecipeDocument, + { id: privateRecipe.id, input: bad }, + owner.cookie, + ) + ).errors, + ); + assert.deepEqual( + (await ok(RecipeDocument, { id: privateRecipe.id }, owner.cookie)) + .recipe, + before, + ); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".recipes`, + ) + ).rows[0].count, + 2, + ); + }, + ); + await t.test( + 'delete cascades; logout revokes later protected calls', + async () => { + await ok(DeleteRecipeDocument, { id: publicRecipe.id }, owner.cookie); + assert.equal( + (await ok(RecipeDocument, { id: publicRecipe.id }, owner.cookie)) + .recipe, + null, + ); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".recipe_ingredients WHERE recipe_id=$1`, + [publicRecipe.id], + ) + ).rows[0].count, + 0, + ); + await ok(SignOutDocument, {}, owner.cookie); + await fails( + CreateRecipeDocument, + { input }, + 'UNAUTHENTICATED', + owner.cookie, + ); + }, + ); + await t.test( + 'demo seed is repeatable and preserves existing passwords', + async () => { + await seedDatabase(pool, 'demo-test-password', schema); + const originalHash = ( + await pool.query( + `SELECT password_hash FROM "${schema}".users WHERE email='demo@example.invalid'`, + ) + ).rows[0].password_hash; + await seedDatabase(pool, 'different-demo-password', schema); + assert.equal( + ( + await pool.query( + `SELECT password_hash FROM "${schema}".users WHERE email='demo@example.invalid'`, + ) + ).rows[0].password_hash, + originalHash, + ); + const demo = await loginSession( + 'demo@example.invalid', + 'demo-test-password', + ); + const cookbook = ( + await ok(CookbookDocument, { scope: 'created' }, demo.cookie) + ).cookbook; + assert.equal(cookbook.totalCount, 2); + assert.equal( + cookbook.items.filter((recipe) => recipe.visibility === 'private') + .length, + 1, + ); + assert.ok( + cookbook.items.every( + (recipe) => + recipe.ingredients.length === 2 && + recipe.instructions.length === 2, + ), + ); + }, + ); + } finally { + try { + 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 new file mode 100644 index 0000000..c532c65 --- /dev/null +++ b/scripts/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "types": ["node"], + "noEmit": true + }, + "include": ["test-recipe-api.ts", "cleanup-images.ts"] +}