Skip to content
Merged
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ http://it2810-03.idi.ntnu.no/project2/

- **Plant Match:** Plants matching the most preferences come first, otherwise the order is random. The deck is kept while the user visits other pages, so they can continue where they left off.
- **My Matches:** Collects liked plants from both Plant Match and Explore Plants. The user only stores plant ids, and the list is fetched one page at a time, so responses do not grow with the number of matches.
- **Explore Plants:** Search, filtering, sorting and pagination run in the backend, so the frontend only receives one page at a time, whatever the size of the collection. The state is kept in the URL, so a view survives a refresh and can be shared as a link.
- **Explore Plants:** Search, filtering, sorting and pagination run in the backend, so the frontend only receives one page at a time, whatever the size of the collection. The state is kept in the URL, so a view survives a refresh and can be shared as a link. Each filter value shows how many plants it would give, and values that would give none can't be chosen, so filtering never ends in an empty list.

## Tech stack

Expand Down
55 changes: 54 additions & 1 deletion backend/src/queryBuilders.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import type { Document, Filter, ObjectId } from "mongodb";
import type { ExplorePlantsArgs, PlantDoc } from "./types.js";
import type {
ExplorePlantsArgs,
FilterCounts,
FilterParam,
PlantDoc,
} from "./types.js";

// Helpers for searching, filtering and sorting plants

Expand Down Expand Up @@ -120,6 +125,54 @@ export const buildExploreFilter = (
return filter;
};

// The values each filter can have. Must match FILTERS in
// frontend/src/pages/explorePlants/ExplorePlantsPage.tsx
export const FILTER_OPTIONS: Record<FilterParam, string[]> = {
watering: ["minimum", "average", "frequent"],
sunlight: ["full_sun", "part_shade", "filtered_shade"],
careLevel: ["low", "medium", "high"],
};

// The name of one count in the $facet result, e.g. "watering:minimum"
const facetKey = (param: string, value: string) => `${param}:${value}`;

// Stages that count, for every filter value, how many plants the user would get
// by choosing it. The value replaces the current choice in that filter, while the
// search and the other filters stay. Uses buildExploreFilter, so the counts
// always agree with the results. All counts are done in one query.
export const buildFilterCountStages = (args: ExplorePlantsArgs): Document[] => {
const facets: Record<string, Document[]> = {};
for (const [param, options] of Object.entries(FILTER_OPTIONS)) {
// "" is "All": nothing chosen in this filter, so only the search and the other filters count
for (const value of ["", ...options]) {
facets[facetKey(param, value)] = [
{ $match: buildExploreFilter({ ...args, [param]: value }) },
{ $count: "count" },
];
}
}
return [
// Only the plants matching the search need to be looked at
{ $match: buildExploreFilter({ search: args.search }) },
{ $facet: facets },
];
};

// Turns the $facet result into the FilterCounts the API returns.
// $count gives an empty list when nothing matches, so that becomes 0.
export const toFilterCounts = (
facets: Record<string, { count: number }[]> = {},
): FilterCounts => {
const counts = {} as FilterCounts;
for (const [param, options] of Object.entries(FILTER_OPTIONS)) {
counts[param as FilterParam] = ["", ...options].map((value) => ({
value,
count: facets[facetKey(param, value)]?.[0]?.count ?? 0,
}));
}
return counts;
};

// Lowercased field value, missing values become ""
const lower = (field: string): Document => ({
$toLower: { $ifNull: [field, ""] },
Expand Down
20 changes: 17 additions & 3 deletions backend/src/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ import type { Document, WithId } from "mongodb";
import { db } from "./db.js";
import {
buildExploreFilter,
buildFilterCountStages,
buildMatchSortStages,
buildSortStages,
matchScore,
PREFERENCE_MATCHERS,
toFilterCounts,
} from "./queryBuilders.js";
import type {
ExplorePlantsArgs,
ExplorePage,
GetPlantsArgs,
MyMatchesArgs,
Plant,
Expand Down Expand Up @@ -181,10 +184,10 @@ export const resolvers = {
explorePlants: async (
_parent: unknown,
args: ExplorePlantsArgs,
): Promise<{ plants: Plant[]; totalCount: number }> => {
): Promise<ExplorePage> => {
const filter = buildExploreFilter(args);

const [docs, totalCount] = await Promise.all([
const [docs, totalCount, [facets]] = await Promise.all([
plants
.aggregate<WithId<PlantDoc>>([
{ $match: filter },
Expand All @@ -194,9 +197,20 @@ export const resolvers = {
])
.toArray(),
plants.countDocuments(filter),
// Match counts for the filter values, so the frontend can show them
// and disable the values that would give no plants
plants
.aggregate<Record<string, { count: number }[]>>(
buildFilterCountStages(args),
)
.toArray(),
]);

return { plants: docs.map(toPlant), totalCount };
return {
plants: docs.map(toPlant),
totalCount,
filterCounts: toFilterCounts(facets),
};
},

getUser: async (
Expand Down
19 changes: 18 additions & 1 deletion backend/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const typeDefs = `
sort: String
limit: Int = 12
offset: Int = 0
): PlantPage!
): ExplorePage!
getUser(userId: ID!): User
myMatches(
userId: ID!
Expand Down Expand Up @@ -38,6 +38,23 @@ export const typeDefs = `
totalCount: Int!
}
type OptionCount {
value: String!
count: Int!
}
type FilterCounts {
watering: [OptionCount!]!
sunlight: [OptionCount!]!
careLevel: [OptionCount!]!
}
type ExplorePage {
plants: [Plant!]!
totalCount: Int!
filterCounts: FilterCounts!
}
type Plant{
id: ID!
name: String!
Expand Down
19 changes: 19 additions & 0 deletions backend/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,25 @@ export interface ExplorePlantsArgs {
offset?: number | null;
}

// The filters on Explore Plants
export type FilterParam = "watering" | "sunlight" | "careLevel";

// How many plants a filter value would give, with the current search and other filters
export interface OptionCount {
value: string;
count: number;
}

export type FilterCounts = Record<FilterParam, OptionCount[]>;

// What explorePlants returns. A separate type from PlantPage, since
// My Matches also uses PlantPage but has no filters to count.
export interface ExplorePage {
plants: Plant[];
totalCount: number;
filterCounts: FilterCounts;
}

// The shape of a user document in MongoDB. _id is added by MongoDB.
export interface UserDoc {
// null means the user has not chosen one, the frontend shows a translated default
Expand Down
65 changes: 65 additions & 0 deletions backend/tests/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,71 @@ describe("plants", () => {
])("sorts with %s", async (sort, expected) => {
expect((await explore({ sort })).names).toEqual(expected);
});

const FILTER_COUNTS = `
query ($search: String, $watering: String) {
explorePlants(search: $search, watering: $watering) {
filterCounts {
watering { value count }
sunlight { value count }
careLevel { value count }
}
}
}
`;

type Counts = Record<string, { value: string; count: number }[]>;

// The counts as { watering: { minimum: 2, ... }, ... }, easier to read in the tests
async function filterCounts(variables: Record<string, unknown> = {}) {
const result = await execute<{ explorePlants: { filterCounts: Counts } }>(
FILTER_COUNTS,
variables,
);
expect(result.errors).toBeUndefined();
return Object.fromEntries(
Object.entries(result.data!.explorePlants.filterCounts).map(
([param, options]) => [
param,
Object.fromEntries(options.map((o) => [o.value, o.count])),
],
),
);
}

it("counts the matches for every filter value", async () => {
expect(await filterCounts()).toEqual({
watering: { "": 6, minimum: 2, average: 2, frequent: 1 },
sunlight: { "": 6, full_sun: 2, part_shade: 2, filtered_shade: 1 },
careLevel: { "": 6, low: 1, medium: 3, high: 1 },
});
});

it("counts with the search and the other filters, but not the filter's own choice", async () => {
const counts = await filterCounts({ watering: "average" });
// Choosing another watering value replaces "average", so these are unchanged
expect(counts.watering).toEqual({
"": 6,
minimum: 2,
average: 2,
frequent: 1,
});
// Only Daisy and Fern (giant) have average watering
expect(counts.sunlight).toEqual({
"": 2,
full_sun: 0,
part_shade: 1,
filtered_shade: 1,
});
expect(counts.careLevel).toEqual({ "": 2, low: 0, medium: 2, high: 0 });

expect((await filterCounts({ search: "fern" })).watering).toEqual({
"": 2,
minimum: 0,
average: 1,
frequent: 0,
});
});
});

describe("users", () => {
Expand Down
15 changes: 8 additions & 7 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f
- `server.ts` starts Apollo Server on `PORT` (default 3001) with the schema and resolvers below.
- `schema.ts` defines the GraphQL schema (`typeDefs`).
- `resolvers.ts` has the resolvers for plants and users, and validates user input.
- `queryBuilders.ts` builds the MongoDB filters and sort stages for searching, filtering and sorting plants on Explore Plants and My Matches.
- `queryBuilders.ts` builds the MongoDB filters and sort stages for searching, filtering and sorting plants on Explore Plants and My Matches, and the counts of how many plants each filter value would give on Explore Plants.
- `indexes.ts` creates the database indexes the app needs when the server starts (see [Scalability](#design-choices-made-for-scalability)).
- `types.ts` has the TypeScript types for the MongoDB documents, the GraphQL types and the resolver arguments.
- `seedDataFetch.js` fills the `plants` collection with plant data (see [Data source](#data-source-the-perenual-api) below).
Expand All @@ -110,12 +110,12 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f

**Queries**

| Query | Description |
| ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getPlants(limit = 50, excludeIds, preferences): [Plant]` | Returns up to `limit` plants (at most 50) for the match page, leaving out the plants in `excludeIds` so each batch only has new plants (malformed ids are ignored). Without `preferences` the order is random (MongoDB `$sample`). With `preferences`, each plant gets a score: the number of the preferences it matches on watering, sunlight and care level ("Low" counts as easy care, "Medium" and "Moderate" as medium care). The highest scores come first and plants with the same score are shuffled. Unknown preferences are ignored. |
| `explorePlants(search, sunlight, watering, careLevel, sort, limit = 12, offset = 0): PlantPage!` | Search on common or scientific name (case-insensitive), filter on sunlight, watering and care level, sort and paginate (`limit` is kept between 1 and 50, and a negative `offset` counts as 0). Returns the plants on the page and `totalCount` for the whole result. Sort can be `name_desc`, `watering_asc` or `careLevel_asc`; the default is name A–Z. |
| `getUser(userId): User` | Returns the user, or `null` if the id is unknown or malformed. |
| `myMatches(userId, sort, limit = 12, offset = 0): PlantPage!` | Returns one page of the user's matched plants and `totalCount` (`limit` and `offset` are kept within the same bounds as in `explorePlants`). Sort can be `oldest`, `name_asc` or `name_desc`; the default is newest first. The order of `matchedPlantIds` is the order the plants were matched, so no date is needed. An unknown or malformed user id gives an empty page. |
| Query | Description |
| -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getPlants(limit = 50, excludeIds, preferences): [Plant]` | Returns up to `limit` plants (at most 50) for the match page, leaving out the plants in `excludeIds` so each batch only has new plants (malformed ids are ignored). Without `preferences` the order is random (MongoDB `$sample`). With `preferences`, each plant gets a score: the number of the preferences it matches on watering, sunlight and care level ("Low" counts as easy care, "Medium" and "Moderate" as medium care). The highest scores come first and plants with the same score are shuffled. Unknown preferences are ignored. |
| `explorePlants(search, sunlight, watering, careLevel, sort, limit = 12, offset = 0): ExplorePage!` | Search on common or scientific name (case-insensitive), filter on sunlight, watering and care level, sort and paginate (`limit` is kept between 1 and 50, and a negative `offset` counts as 0). Returns the plants on the page and `totalCount` for the whole result. Sort can be `name_desc`, `watering_asc` or `careLevel_asc`; the default is name A–Z. Also returns `filterCounts`: for every filter value, and for "All" (an empty value), the number of plants it would give instead of the current choice in the same filter, together with the search and the other filters. The counts use the same filter as the results, so they always agree, and are done in one `$facet` aggregation. |
| `getUser(userId): User` | Returns the user, or `null` if the id is unknown or malformed. |
| `myMatches(userId, sort, limit = 12, offset = 0): PlantPage!` | Returns one page of the user's matched plants and `totalCount` (`limit` and `offset` are kept within the same bounds as in `explorePlants`). Sort can be `oldest`, `name_asc` or `name_desc`; the default is newest first. The order of `matchedPlantIds` is the order the plants were matched, so no date is needed. An unknown or malformed user id gives an empty page. |

**Mutations**

Expand All @@ -131,6 +131,7 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f

- `Plant`: `id`, `name`, `imageURL`, `scientificName`, `description`, `watering`, `sunlight`, `careLevel`
- `PlantPage`: `plants`, `totalCount`
- `ExplorePage`: `plants`, `totalCount`, `filterCounts`. `FilterCounts` has `watering`, `sunlight` and `careLevel`, each a list of `OptionCount` (`value`, `count`). Explore has its own type, since My Matches also uses `PlantPage` but has no filters to count.
- `User`: `id`, `name`, `description`, `profilePicture`, `preferences`, `matchedPlantIds`, `createdAt`

`User.matchedPlantIds` only returns the ids, so the pages that just need to know whether a plant is matched do not fetch the whole plants with images. The plants themselves are fetched one page at a time with `myMatches`, which only shows and counts plants that still exist (for example after a reseed).
Expand Down
Loading
Loading