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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Recipe Platform er en responsiv oppskriftsapplikasjon hvor brukere kan utforske
- 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 kan sorteres med nyeste først, kortest tilberedningstid eller høyest vurdering.
- Ordsøk i tittel, beskrivelse, ingredienser og tagger (alle ord må finnes), kategori- og tidsfilter samt paginering utføres i backend. Resultatene kan sorteres med nyeste først, kortest tilberedningstid eller høyest vurdering.
- 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 51 demooppskrifter inkludert bilder; et større eksternt datasett er ikke importert. Se [kjente begrensninger](#kjente-begrensninger).
Expand Down Expand Up @@ -176,17 +176,18 @@ Oppsett for CI-testdatabase, migrasjoner og utrulling er samlet i [drift og test

## Nyttige kommandoer

| Kommando | Bruk |
| ---------------------- | ------------------------------------------- |
| `npm run dev` | Start utviklingsmiljøet |
| `npm run dev:web` | Start bare React-klienten |
| `npm run dev:api` | Start bare API-et |
| `npm run typecheck` | Kontroller TypeScript i frontend og backend |
| `npm run lint` | Kjør ESLint |
| `npm run format` | Formater kode med Prettier |
| `npm run format:check` | Kontroller formatering uten å endre filer |
| `npm run test` | Kjør Vitest-testene |
| `npm run build` | Bygg workspaces for produksjon |
| Kommando | Bruk |
| --------------------------------- | -------------------------------------------------------- |
| `npm run dev` | Start utviklingsmiljøet |
| `npm run dev:web` | Start bare React-klienten |
| `npm run dev:api` | Start bare API-et |
| `npm run typecheck` | Kontroller TypeScript i frontend og backend |
| `npm run lint` | Kjør ESLint |
| `npm run format` | Formater kode med Prettier |
| `npm run format:check` | Kontroller formatering uten å endre filer |
| `npm run test` | Kjør Vitest-testene |
| `npm run build` | Bygg workspaces for produksjon |
| `npm run db:seed:large -- 100000` | Last 100 000 testoppskrifter (`-- --remove` fjerner dem) |

Før en Pull Request bør minst følgende kjøres:

Expand Down Expand Up @@ -399,10 +400,10 @@ KI-verktøy får ikke ekte passord, tokens, personopplysninger eller andre hemme

## Kjente begrensninger

- Søk dekker tittel og beskrivelse; ingrediens- og tagsøk er videre arbeid.
- Trending er ikke implementert. Høyest vurdering bruker gjennomsnittet uten vekting etter antall stemmer.
- Utkast lagres bare i nettleseren (localStorage) per bruker og oppskrift, ikke på serveren, og følger derfor ikke brukeren til en annen enhet. De slettes ved utlogging.
- Seed inneholder 51 demooppskrifter og demonstrerer ikke ytelse med store datamengder.
- Ytelse er målt lokalt med 100 000 genererte oppskrifter (`npm run db:seed:large`) i en egen testdatabase, ikke på VM-en. Se [søk og skalerbarhet](docs/performance-and-images.md#søk-og-skalerbarhet).
- Søk finner hele ord og begynnelsen av ord, ikke deler midt i et ord («cake» finner ikke «pancakes»).
- 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 HTTP. Foreleser har avklart at HTTPS ikke er et krav for denne innleveringen, men det er nødvendig for å beskytte innlogging under transport. Bruk bare testpassord.
Expand Down
131 changes: 131 additions & 0 deletions apps/api/migrations/0005_recipe_search_and_ratings.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
ALTER TABLE "project2"."recipes" ADD COLUMN "rating_avg" numeric;--> statement-breakpoint
ALTER TABLE "project2"."recipes" ADD COLUMN "rating_count" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
ALTER TABLE "project2"."recipes" ADD COLUMN "search_vector" "tsvector" DEFAULT ''::tsvector NOT NULL;--> statement-breakpoint
CREATE INDEX "recipes_public_category_created_idx" ON "project2"."recipes" USING btree ("category","created_at" DESC NULLS FIRST,"id" DESC NULLS FIRST) WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint
CREATE INDEX "recipes_public_total_time_idx" ON "project2"."recipes" USING btree (("prep_minutes" + "cook_minutes"),"created_at" DESC NULLS FIRST,"id" DESC NULLS FIRST) WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint
CREATE INDEX "recipes_public_rating_idx" ON "project2"."recipes" USING btree ("rating_avg" DESC NULLS LAST,"created_at" DESC NULLS FIRST,"id" DESC NULLS FIRST) WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint
CREATE INDEX "recipes_search_idx" ON "project2"."recipes" USING gin ("search_vector");
--> statement-breakpoint
-- Keep recipes.rating_avg/rating_count in step with ratings for every write
-- path (API, seed, manual SQL), so the highest-rated sort can use an index.
-- The recipe row is locked before counting. A concurrent rating of the same
-- recipe then waits until this one commits, and its count (a new snapshot,
-- since this is a separate statement) includes this rating instead of
-- overwriting the cache with a stale value. A rating moved to another recipe
-- refreshes both recipes, locked in id order so two moves cannot deadlock.
CREATE FUNCTION "project2"."refresh_recipe_rating"() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
target uuid;
BEGIN
FOR target IN
SELECT DISTINCT changed.id FROM unnest(ARRAY[
CASE WHEN TG_OP <> 'INSERT' THEN OLD.recipe_id END,
CASE WHEN TG_OP <> 'DELETE' THEN NEW.recipe_id END
]) AS changed(id)
WHERE changed.id IS NOT NULL ORDER BY changed.id
LOOP
PERFORM 1 FROM "project2"."recipes" WHERE id = target FOR NO KEY UPDATE;
UPDATE "project2"."recipes" r
SET rating_avg = s.average, rating_count = s.total
FROM (
SELECT avg(score) AS average, count(*)::int AS total
FROM "project2"."ratings" WHERE recipe_id = target
) s
WHERE r.id = target;
END LOOP;
RETURN NULL;
END $$;
--> statement-breakpoint
CREATE TRIGGER ratings_refresh_recipe_rating
AFTER INSERT OR UPDATE OF score, recipe_id OR DELETE ON "project2"."ratings"
FOR EACH ROW EXECUTE FUNCTION "project2"."refresh_recipe_rating"();
--> statement-breakpoint
-- Backfill existing ratings.
UPDATE "project2"."recipes" r
SET rating_avg = s.average, rating_count = s.total
FROM (
SELECT recipe_id, avg(score) AS average, count(*)::int AS total
FROM "project2"."ratings" GROUP BY recipe_id
) s
WHERE r.id = s.recipe_id;
--> statement-breakpoint
-- A new rating must not change the recipe's "last updated" time: fire the
-- touch trigger only when recipe content (or updated_at itself) is written.
DROP TRIGGER recipes_touch_updated_at ON "project2"."recipes";
--> statement-breakpoint
CREATE TRIGGER recipes_touch_updated_at
BEFORE UPDATE OF title, description, image_url, category, cuisine, difficulty,
visibility, prep_minutes, cook_minutes, servings, source_recipe_id, author_id,
updated_at
ON "project2"."recipes"
FOR EACH ROW EXECUTE FUNCTION "project2"."touch_updated_at"();
--> statement-breakpoint
-- Full-text search document: title, description, ingredient names and tags.
CREATE FUNCTION "project2"."recipe_search_document"(recipe uuid, title text, description text)
RETURNS tsvector LANGUAGE sql STABLE AS $$
SELECT to_tsvector('simple', concat_ws(' ', title, description,
(SELECT string_agg(i.name, ' ') FROM "project2"."recipe_ingredients" i WHERE i.recipe_id = recipe),
(SELECT string_agg(t.tag, ' ') FROM "project2"."recipe_tags" t WHERE t.recipe_id = recipe)))
$$;
--> statement-breakpoint
CREATE FUNCTION "project2"."set_recipe_search_vector"() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.search_vector := "project2"."recipe_search_document"(NEW.id, NEW.title, NEW.description);
RETURN NEW;
END $$;
--> statement-breakpoint
CREATE TRIGGER recipes_set_search_vector
BEFORE INSERT OR UPDATE OF title, description ON "project2"."recipes"
FOR EACH ROW EXECUTE FUNCTION "project2"."set_recipe_search_vector"();
--> statement-breakpoint
-- Statement-level: one refresh per INSERT/UPDATE/DELETE statement on
-- ingredients or tags, for every recipe the statement touched. An UPDATE that
-- moves rows to another recipe refreshes both the old and the new recipe.
-- As for ratings, the recipes are locked (in id order, so concurrent writers
-- cannot deadlock) before the document is rebuilt in a new snapshot, so a
-- concurrent ingredient or tag write is never overwritten by stale words.
CREATE FUNCTION "project2"."refresh_recipe_search_vector"() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
targets uuid[];
BEGIN
IF TG_OP = 'INSERT' THEN
SELECT array_agg(DISTINCT recipe_id) INTO targets FROM new_rows;
ELSIF TG_OP = 'DELETE' THEN
SELECT array_agg(DISTINCT recipe_id) INTO targets FROM old_rows;
ELSE
SELECT array_agg(recipe_id) INTO targets FROM (
SELECT recipe_id FROM old_rows UNION SELECT recipe_id FROM new_rows
) touched;
END IF;
PERFORM 1 FROM "project2"."recipes"
WHERE id = ANY(targets) ORDER BY id FOR NO KEY UPDATE;
UPDATE "project2"."recipes" r
SET search_vector = "project2"."recipe_search_document"(r.id, r.title, r.description)
WHERE r.id = ANY(targets);
RETURN NULL;
END $$;
--> statement-breakpoint
CREATE TRIGGER recipe_ingredients_search_insert AFTER INSERT ON "project2"."recipe_ingredients"
REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"();
--> statement-breakpoint
CREATE TRIGGER recipe_ingredients_search_update AFTER UPDATE ON "project2"."recipe_ingredients"
REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"();
--> statement-breakpoint
CREATE TRIGGER recipe_ingredients_search_delete AFTER DELETE ON "project2"."recipe_ingredients"
REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"();
--> statement-breakpoint
CREATE TRIGGER recipe_tags_search_insert AFTER INSERT ON "project2"."recipe_tags"
REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"();
--> statement-breakpoint
CREATE TRIGGER recipe_tags_search_update AFTER UPDATE ON "project2"."recipe_tags"
REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"();
--> statement-breakpoint
CREATE TRIGGER recipe_tags_search_delete AFTER DELETE ON "project2"."recipe_tags"
REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"();
--> statement-breakpoint
-- Backfill existing recipes.
UPDATE "project2"."recipes"
SET search_vector = "project2"."recipe_search_document"(id, title, description);
Loading