diff --git a/docs/architecture.md b/docs/architecture.md index 2a356927..31cc59d7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -48,16 +48,76 @@ The frontend is built with React and TypeScript (Vite). | `/plantOwnerTest` | `PlantOwnerTest` | A quiz whose result can be set as the profile picture | | `*` | `NotFound` | 404 page for unknown paths, with a link back to Plant Match | -- **User state:** `UserProvider` (`context/UserContext.tsx`) loads the current user from the backend and makes it available through `useUser()`. The hooks `useProfile` and `useMatchedPlants` wrap the user mutations, so pages do not call GraphQL directly for user data. All user queries and mutations live in `context/userQueries.ts`. +- **User state:** `UserProvider` (`context/UserContext.tsx`) loads the current user from the backend and makes it available through `useUser()`. The hooks `useProfile` and `useMatchedPlants` wrap the user mutations, so pages do not call GraphQL directly for user data. The user queries and mutations themselves live in `graphql/user/` (see [GraphQL operations](#graphql-operations-in-the-frontend)). - **Reusable logic in hooks:** Logic without UI is kept in hooks. `useDebounce` delays updates while the user is typing (used for search and for saving the profile text). `useExploreParams` keeps the Explore search, filters, sort order and page in the URL, and sends the user back to page 1 when the search, a filter or the sort order changes. It uses `useUrlParams`, which reads the page number and updates the URL (with React Router's `useSearchParams`). `useSessionState` stores state in `sessionStorage`, for example the sort order on My Matches. - **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, and always shows the first and last page with "…" in between, so it works for any number of pages (`getPageItems`). `FilterSelect` is a labelled dropdown for one filter. `SortMenu` is a sort button that shows the selected option and opens a menu that can be used with the keyboard. All three take already translated texts, so they can be used on other pages. - **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next). -- **Shared types:** `Plant` and `Preference` are defined in `types/`. +- **Shared types:** `Plant`, `User` and `Preference` are defined in `types/`. ### Communication with the backend The frontend uses Apollo Client, which is set up in `main.tsx` with an in-memory cache. The GraphQL URL is read from `VITE_GRAPHQL_URL` (set in `frontend/.env.production` for the deployed app) and falls back to `/graphql`. During development, requests to `/graphql` are proxied by Vite to the backend on port 3001 (see [vite.config.ts](../frontend/vite.config.ts)). +### GraphQL operations in the frontend + +All GraphQL queries, mutations and fragments in the frontend are collected in `frontend/src/graphql/`, grouped by domain the same way as the backend schema: + +```text +graphql/ +├── fragments/ +│ ├── plantFragments.ts # PlantFields: the plant fields every plant list asks for +│ └── userFragments.ts # UserFields: the user fields every user operation returns (uses PlantFields for matchedPlants) +├── plants/ +│ └── queries.ts # GET_PLANTS (Plant Match deck), EXPLORE_PLANTS (Explore Plants) +└── user/ + ├── queries.ts # GET_USER + └── mutations.ts # CREATE_USER, ADD_USER_MATCH, REMOVE_USER_MATCH, UPDATE_USER_PROFILE, UPDATE_USER_PREFERENCES +``` + +Each file also exports the TypeScript type for the result of its operations (for example `GetPlantsData` and `ExplorePlantsData`). The shared `Plant` and `User` types are in `types/`. Pages, hooks and the context only import the operations they use, for example `usePlantDeck` imports `GET_PLANTS` and `useMatchedPlants` imports `ADD_USER_MATCH` and `REMOVE_USER_MATCH`. + +Earlier the operations were spread across three places: the user operations in `context/userQueries.ts`, `EXPLORE_PLANTS` next to the Explore Plants page and `GET_PLANTS` inside the `usePlantDeck` hook. We moved them into one folder after feedback, and because one of our main goals is that the app should scale: + +- **One place to look.** All requests the frontend can send are in one folder, so it is easy to compare them with the backend schema and to see what a schema change affects. +- **The user operations are shared.** They are used by `UserProvider`, two hooks and a component, so they do not belong to any one of them. Keeping them in `context/` made it look like they were part of the context. +- **One rule for new features.** A new domain (for example comments) gets its own folder, such as `graphql/comments/`, instead of each developer deciding where its queries should go. +- **Shared fragments.** The plant fields used to be written out three times (in `getPlants`, `explorePlants` and the user's `matchedPlants`). They are now defined once in `PlantFields`, so a new plant field only has to be added in one place, and every plant in the Apollo cache has the same fields. +- **Ready for code generation.** Because all operations are in one folder, a tool like GraphQL Code Generator could later generate the result types from the backend schema (`documents: "src/graphql/**/*.ts"`) instead of us writing them by hand. + +We considered keeping each query next to the component that uses it (colocation), which is common in large apps organised by feature. Our frontend is organised by technical role (`pages/`, `components/`, `hooks/`, `context/`), and most of our operations are used in more than one place, so a shared folder fits better. If the app is later reorganised into feature folders, each domain folder in `graphql/` can be moved into its feature. + +### Apollo cache + +### GraphQL operations in the frontend + +All GraphQL queries, mutations and fragments in the frontend are collected in `frontend/src/graphql/`, grouped by domain the same way as the backend schema: + +```text +graphql/ +├── fragments/ +│ ├── plantFragments.ts # PlantFields: the plant fields every plant list asks for +│ └── userFragments.ts # UserFields: the user fields every user operation returns (uses PlantFields for matchedPlants) +├── plants/ +│ └── queries.ts # GET_PLANTS (Plant Match deck), EXPLORE_PLANTS (Explore Plants) +└── user/ + ├── queries.ts # GET_USER + └── mutations.ts # CREATE_USER, ADD_USER_MATCH, REMOVE_USER_MATCH, UPDATE_USER_PROFILE, UPDATE_USER_PREFERENCES +``` + +Each file also exports the TypeScript type for the result of its operations (for example `GetPlantsData` and `ExplorePlantsData`). The shared `Plant` and `User` types are in `types/`. Pages, hooks and the context only import the operations they use, for example `usePlantDeck` imports `GET_PLANTS` and `useMatchedPlants` imports `ADD_USER_MATCH` and `REMOVE_USER_MATCH`. + +Earlier the operations were spread across three places: the user operations in `context/userQueries.ts`, `EXPLORE_PLANTS` next to the Explore Plants page and `GET_PLANTS` inside the `usePlantDeck` hook. We moved them into one folder after feedback, and because one of our main goals is that the app should scale: + +- **One place to look.** All requests the frontend can send are in one folder, so it is easy to compare them with the backend schema and to see what a schema change affects. +- **The user operations are shared.** They are used by `UserProvider`, two hooks and a component, so they do not belong to any one of them. Keeping them in `context/` made it look like they were part of the context. +- **One rule for new features.** A new domain (for example comments) gets its own folder, such as `graphql/comments/`, instead of each developer deciding where its queries should go. +- **Shared fragments.** The plant fields used to be written out three times (in `getPlants`, `explorePlants` and the user's `matchedPlants`). They are now defined once in `PlantFields`, so a new plant field only has to be added in one place, and every plant in the Apollo cache has the same fields. +- **Ready for code generation.** Because all operations are in one folder, a tool like GraphQL Code Generator could later generate the result types from the backend schema (`documents: "src/graphql/**/*.ts"`) instead of us writing them by hand. + +We considered keeping each query next to the component that uses it (colocation), which is common in large apps organised by feature. Our frontend is organised by technical role (`pages/`, `components/`, `hooks/`, `context/`), and most of our operations are used in more than one place, so a shared folder fits better. If the app is later reorganised into feature folders, each domain folder in `graphql/` can be moved into its feature. + +### Apollo cache + All user queries and mutations ask for the same `UserFields` fragment, so when one page changes the user (for example adds a match), Apollo's cache updates the user on every page at once. Changing the profile picture uses an optimistic response, so the new picture is shown before the server has answered. The fragment only has the ids of the matched plants (`matchedPlantIds`), so the user stays small however many matches there are. Adding and removing a match returns the whole list of ids, so the cache replaces it instead of merging it with the old list. My Matches fetches its plants with its own `myMatches` query, which is fetched again when a match is added or removed, and every time the page is opened. ## Backend: GraphQL with Apollo Server @@ -202,6 +262,7 @@ When the app starts, `UserProvider` reads `userId` from `localStorage` and runs - **Sorting by watering and care level:** These use a calculated rank, since the values cannot be sorted alphabetically (Minimum, Average, Frequent), and plants without a value are put last. A calculated rank cannot use an index. If the collection grows much larger, the rank could be calculated once when the data is loaded, stored on each plant and indexed. - **Offset-based pagination.** We use offset-based pagination (`$skip` and `$limit`) instead of cursor-based pagination, because it lets the user jump to any page and works with all our sort orders, including the ones on calculated values. Offset pagination gets slower for very deep pages, but that only matters for collections far larger than ours. - **Small responses.** GraphQL returns only the requested fields, and fields we do not use are kept out of the schema. +- **GraphQL operations in one folder.** All queries, mutations and fragments are in `frontend/src/graphql/`, grouped by domain, with shared fragments for the plant and user fields. New features get their own folder, and a schema change only has to be followed up in one place (see [GraphQL operations](#graphql-operations-in-the-frontend)). - **Small user documents and responses.** Matches are stored as plant ids, and user updates only touch one document. Only the ids are sent with the user, and My Matches fetches one page of plants at a time, so the responses do not grow with the number of matches. - **Less traffic from the client.** Search input is debounced, results are cached by Apollo, and pages other than the start page are lazy-loaded. - **Limitation: plant images are stored as base64 in the database.** Each plant image is stored as a base64 data URI in `imageData` (see [Data source: the Perenual API](#data-source-the-perenual-api)), instead of as an image file on the VM. This limits how well the solution scales: @@ -254,12 +315,13 @@ T03-Project-2/ │ ├── src/ │ │ ├── assets/ # Static images │ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file -│ │ ├── context/ # UserProvider and the GraphQL queries and mutations for the user +│ │ ├── context/ # UserProvider and useUser() for the current user +│ │ ├── graphql/ # All GraphQL queries, mutations and fragments, grouped by domain (fragments/, plants/, user/) │ │ ├── hooks/ # Reusable logic without UI (useDebounce, useUrlParams, useExploreParams, useSessionState, useProfile, useMatchedPlants, usePlantDeck) │ │ ├── i18n/ # Translation setup and locale files (no, en) │ │ ├── pages/ # One folder per page/route with a matching .css file │ │ ├── tests/ # Unit and component tests, including test setup (see tests.md) -│ │ ├── types/ # Shared TypeScript types (Plant, Preference) +│ │ ├── types/ # Shared TypeScript types (Plant, User, Preference) │ │ ├── AppRoutes.tsx # Route definitions │ │ └── main.tsx # Application entry point (Apollo Client, UserProvider, router) │ ├── .env.production # GraphQL URL for the deployed app diff --git a/frontend/src/components/plantPreferences/PlantPreferences.tsx b/frontend/src/components/plantPreferences/PlantPreferences.tsx index b381e20e..69f306c7 100644 --- a/frontend/src/components/plantPreferences/PlantPreferences.tsx +++ b/frontend/src/components/plantPreferences/PlantPreferences.tsx @@ -4,7 +4,7 @@ import { useUser } from "../../context/UserContext.tsx"; import { UPDATE_USER_PREFERENCES, type UpdateUserPreferencesData, -} from "../../context/userQueries.ts"; +} from "../../graphql/user/mutations.ts"; import type { Preference } from "../../types/Preference.ts"; import "./PlantPreferences.css"; diff --git a/frontend/src/context/UserContext.tsx b/frontend/src/context/UserContext.tsx index eff82948..72152d25 100644 --- a/frontend/src/context/UserContext.tsx +++ b/frontend/src/context/UserContext.tsx @@ -7,13 +7,9 @@ import { useState, type ReactNode, } from "react"; -import { - CREATE_USER, - GET_USER, - type CreateUserData, - type GetUserData, - type User, -} from "./userQueries"; +import { GET_USER, type GetUserData } from "../graphql/user/queries"; +import { CREATE_USER, type CreateUserData } from "../graphql/user/mutations"; +import type { User } from "../types/User"; // The only user data kept in the browser. Everything else is in the database. const STORAGE_KEY = "userId"; diff --git a/frontend/src/graphql/fragments/plantFragments.ts b/frontend/src/graphql/fragments/plantFragments.ts new file mode 100644 index 00000000..90ea20c8 --- /dev/null +++ b/frontend/src/graphql/fragments/plantFragments.ts @@ -0,0 +1,16 @@ +import { gql } from "@apollo/client"; + +// The plant fields every plant list asks for. Using the same fields everywhere +// keeps the Plant type, the Apollo cache and the plant cards consistent. +export const PLANT_FIELDS = gql` + fragment PlantFields on Plant { + id + name + imageURL + scientificName + description + watering + sunlight + careLevel + } +`; diff --git a/frontend/src/graphql/fragments/userFragments.ts b/frontend/src/graphql/fragments/userFragments.ts new file mode 100644 index 00000000..853c92d9 --- /dev/null +++ b/frontend/src/graphql/fragments/userFragments.ts @@ -0,0 +1,18 @@ +import { gql } from "@apollo/client"; +import { PLANT_FIELDS } from "./plantFragments"; + +// The user fields every query and mutation asks for. Using the same fields +// everywhere lets Apollo's cache update the user on all pages at once. +export const USER_FIELDS = gql` + fragment UserFields on User { + id + name + description + profilePicture + preferences + matchedPlants { + ...PlantFields + } + } + ${PLANT_FIELDS} +`; diff --git a/frontend/src/graphql/plants/queries.ts b/frontend/src/graphql/plants/queries.ts new file mode 100644 index 00000000..184da1d5 --- /dev/null +++ b/frontend/src/graphql/plants/queries.ts @@ -0,0 +1,53 @@ +import { gql } from "@apollo/client"; +import type { Plant } from "../../types/Plant"; +import { PLANT_FIELDS } from "../fragments/plantFragments"; + +// Used by the Plant Match deck (usePlantDeck). Plants already in the deck are +// excluded, and plants matching the most preferences come first. +export const GET_PLANTS = gql` + query GetPlants($limit: Int, $excludeIds: [ID!], $preferences: [String!]) { + getPlants( + limit: $limit + excludeIds: $excludeIds + preferences: $preferences + ) { + ...PlantFields + } + } + ${PLANT_FIELDS} +`; + +// Used by the ExplorePlants page. Search, filtering, sorting and pagination +// all happen in the backend, so they apply to the whole dataset. +export const EXPLORE_PLANTS = gql` + query ExplorePlants( + $search: String + $sunlight: String + $watering: String + $careLevel: String + $sort: String + $limit: Int + $offset: Int + ) { + explorePlants( + search: $search + sunlight: $sunlight + watering: $watering + careLevel: $careLevel + sort: $sort + limit: $limit + offset: $offset + ) { + totalCount + plants { + ...PlantFields + } + } + } + ${PLANT_FIELDS} +`; + +export type GetPlantsData = { getPlants: Plant[] }; +export type ExplorePlantsData = { + explorePlants: { totalCount: number; plants: Plant[] }; +}; diff --git a/frontend/src/context/userQueries.ts b/frontend/src/graphql/user/mutations.ts similarity index 72% rename from frontend/src/context/userQueries.ts rename to frontend/src/graphql/user/mutations.ts index 757e8c14..67e1fc31 100644 --- a/frontend/src/context/userQueries.ts +++ b/frontend/src/graphql/user/mutations.ts @@ -1,27 +1,6 @@ import { gql } from "@apollo/client"; -import type { Plant } from "../types/Plant"; - -// The user fields every query and mutation asks for. Using the same fields -// everywhere lets Apollo's cache update the user on all pages at once. -const USER_FIELDS = gql` - fragment UserFields on User { - id - name - description - profilePicture - preferences - matchedPlantIds - } -`; - -export const GET_USER = gql` - query GetUser($userId: ID!) { - getUser(userId: $userId) { - ...UserFields - } - } - ${USER_FIELDS} -`; +import type { User } from "../../types/User"; +import { USER_FIELDS } from "../fragments/userFragments"; // One page of the user's matched plants, sorted. Only My Matches uses this, // so the other pages don't have to fetch the whole plants with images. @@ -100,20 +79,6 @@ export const UPDATE_USER_PREFERENCES = gql` } `; -// A user as returned by the queries above -export type User = { - id: string; - name: string | null; - description: string | null; - profilePicture: string; - preferences: string[]; - matchedPlantIds: string[]; -}; - -export type GetUserData = { getUser: User | null }; -export type MyMatchesData = { - myMatches: { totalCount: number; plants: Plant[] }; -}; export type CreateUserData = { createUser: User }; export type AddUserMatchData = { addUserMatch: User | null }; export type RemoveUserMatchData = { removeUserMatch: User | null }; diff --git a/frontend/src/graphql/user/queries.ts b/frontend/src/graphql/user/queries.ts new file mode 100644 index 00000000..08f2caf1 --- /dev/null +++ b/frontend/src/graphql/user/queries.ts @@ -0,0 +1,14 @@ +import { gql } from "@apollo/client"; +import type { User } from "../../types/User"; +import { USER_FIELDS } from "../fragments/userFragments"; + +export const GET_USER = gql` + query GetUser($userId: ID!) { + getUser(userId: $userId) { + ...UserFields + } + } + ${USER_FIELDS} +`; + +export type GetUserData = { getUser: User | null }; diff --git a/frontend/src/hooks/useMatchedPlants.ts b/frontend/src/hooks/useMatchedPlants.ts index a1150583..3e650525 100644 --- a/frontend/src/hooks/useMatchedPlants.ts +++ b/frontend/src/hooks/useMatchedPlants.ts @@ -5,7 +5,7 @@ import { REMOVE_USER_MATCH, type AddUserMatchData, type RemoveUserMatchData, -} from "../context/userQueries"; +} from "../graphql/user/mutations"; import type { Plant } from "../types/Plant"; // My Matches is fetched again after a match is added or removed, so the list diff --git a/frontend/src/hooks/usePlantDeck.ts b/frontend/src/hooks/usePlantDeck.ts index aa612c07..7d1688f0 100644 --- a/frontend/src/hooks/usePlantDeck.ts +++ b/frontend/src/hooks/usePlantDeck.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; -import { gql } from "@apollo/client"; import { useApolloClient } from "@apollo/client/react"; import { useUser } from "../context/UserContext"; +import { GET_PLANTS, type GetPlantsData } from "../graphql/plants/queries"; import type { Plant } from "../types/Plant"; // How many plants are fetched per request. Keep it between 5 and 10. @@ -10,29 +10,6 @@ export const PLANT_BATCH_SIZE = 8; // The next batch is fetched when this many cards (or fewer) are left in the deck export const PREFETCH_THRESHOLD = 3; -export const GET_PLANTS = gql` - query GetPlants($limit: Int, $excludeIds: [ID!], $preferences: [String!]) { - getPlants( - limit: $limit - excludeIds: $excludeIds - preferences: $preferences - ) { - id - name - imageURL - scientificName - description - watering - sunlight - careLevel - } - } -`; - -export type GetPlantsData = { - getPlants: Plant[]; -}; - // A deck of plants that is loaded in small batches while the user swipes. // Plants already in the deck are excluded by the backend, so a plant is never // shown twice while the page is open. Plants matching the most of the user's diff --git a/frontend/src/hooks/useProfile.ts b/frontend/src/hooks/useProfile.ts index 532a3415..9771fde9 100644 --- a/frontend/src/hooks/useProfile.ts +++ b/frontend/src/hooks/useProfile.ts @@ -4,7 +4,7 @@ import { useUser } from "../context/UserContext"; import { UPDATE_USER_PROFILE, type UpdateUserProfileData, -} from "../context/userQueries"; +} from "../graphql/user/mutations"; import { useDebounce } from "./useDebounce"; type ProfileDraft = { name?: string; description?: string }; diff --git a/frontend/src/pages/explorePlants/ExplorePlants.tsx b/frontend/src/pages/explorePlants/ExplorePlants.tsx index 897cada7..6af308fe 100644 --- a/frontend/src/pages/explorePlants/ExplorePlants.tsx +++ b/frontend/src/pages/explorePlants/ExplorePlants.tsx @@ -6,7 +6,7 @@ import { useExploreParams } from "../../hooks/useExploreParams.ts"; import { EXPLORE_PLANTS, type ExplorePlantsData, -} from "./explorePlantsQuery.ts"; +} from "../../graphql/plants/queries.ts"; import PlantCard from "../../components/plantCard/PlantCard.tsx"; import Pagination from "../../components/pagination/Pagination.tsx"; import FilterSelect from "../../components/filterSelect/FilterSelect.tsx"; diff --git a/frontend/src/pages/explorePlants/explorePlantsQuery.ts b/frontend/src/pages/explorePlants/explorePlantsQuery.ts deleted file mode 100644 index e0509753..00000000 --- a/frontend/src/pages/explorePlants/explorePlantsQuery.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { gql } from "@apollo/client"; - -// Query used by the ExplorePlants page. Search, filtering, sorting and pagination -// all happen in the backend, so they apply to the whole dataset. -export const EXPLORE_PLANTS = gql` - query ExplorePlants( - $search: String - $sunlight: String - $watering: String - $careLevel: String - $sort: String - $limit: Int - $offset: Int - ) { - explorePlants( - search: $search - sunlight: $sunlight - watering: $watering - careLevel: $careLevel - sort: $sort - limit: $limit - offset: $offset - ) { - totalCount - plants { - id - name - imageURL - scientificName - description - watering - sunlight - careLevel - } - } - } -`; - -export type ExplorePlantsData = { - explorePlants: { - totalCount: number; - plants: { - id: string; - name: string | null; - imageURL: string | null; - scientificName: string[] | null; - description: string | null; - watering: string | null; - sunlight: string[] | null; - careLevel: string | null; - }[]; - }; -}; diff --git a/frontend/src/tests/ExplorePage.test.tsx b/frontend/src/tests/ExplorePage.test.tsx index 67363b40..2f28aa8e 100644 --- a/frontend/src/tests/ExplorePage.test.tsx +++ b/frontend/src/tests/ExplorePage.test.tsx @@ -5,7 +5,7 @@ import { MockedProvider } from "@apollo/client/testing/react"; import { MemoryRouter, useLocation } from "react-router-dom"; import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import ExplorePlants from "../pages/explorePlants/ExplorePlants"; -import { EXPLORE_PLANTS } from "../pages/explorePlants/explorePlantsQuery"; +import { EXPLORE_PLANTS } from "../graphql/plants/queries"; // Mock i18next: return the key as the translation, with the count for the number // of results and the page numbers for the page counter diff --git a/frontend/src/tests/UserContext.test.tsx b/frontend/src/tests/UserContext.test.tsx index e8d9e375..b8471333 100644 --- a/frontend/src/tests/UserContext.test.tsx +++ b/frontend/src/tests/UserContext.test.tsx @@ -3,7 +3,8 @@ import { render, screen, waitFor } from "@testing-library/react"; import { MockedProvider } from "@apollo/client/testing/react"; import { beforeEach, describe, it, expect, vi } from "vitest"; import { UserProvider, useUser } from "../context/UserContext"; -import { CREATE_USER, GET_USER } from "../context/userQueries"; +import { GET_USER } from "../graphql/user/queries"; +import { CREATE_USER } from "../graphql/user/mutations"; type Mocks = ComponentProps["mocks"]; diff --git a/frontend/src/types/Plant.ts b/frontend/src/types/Plant.ts index fa2af0f3..467d41d3 100644 --- a/frontend/src/types/Plant.ts +++ b/frontend/src/types/Plant.ts @@ -1,4 +1,4 @@ -// A plant as returned by the getPlants query. +// A plant as returned by the plant queries (the PlantFields fragment). export type Plant = { id: string; name: string | null; diff --git a/frontend/src/types/User.ts b/frontend/src/types/User.ts new file mode 100644 index 00000000..7bf56666 --- /dev/null +++ b/frontend/src/types/User.ts @@ -0,0 +1,11 @@ +import type { Plant } from "./Plant"; + +// A user as returned by the user queries and mutations (the UserFields fragment). +export type User = { + id: string; + name: string | null; + description: string | null; + profilePicture: string; + preferences: string[]; + matchedPlants: Plant[]; +};