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
70 changes: 66 additions & 4 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down
10 changes: 3 additions & 7 deletions frontend/src/context/UserContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
16 changes: 16 additions & 0 deletions frontend/src/graphql/fragments/plantFragments.ts
Original file line number Diff line number Diff line change
@@ -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
}
`;
18 changes: 18 additions & 0 deletions frontend/src/graphql/fragments/userFragments.ts
Original file line number Diff line number Diff line change
@@ -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}
`;
53 changes: 53 additions & 0 deletions frontend/src/graphql/plants/queries.ts
Original file line number Diff line number Diff line change
@@ -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[] };
};
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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 };
Expand Down
14 changes: 14 additions & 0 deletions frontend/src/graphql/user/queries.ts
Original file line number Diff line number Diff line change
@@ -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 };
2 changes: 1 addition & 1 deletion frontend/src/hooks/useMatchedPlants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 1 addition & 24 deletions frontend/src/hooks/usePlantDeck.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/hooks/useProfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/pages/explorePlants/ExplorePlants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Loading
Loading