Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ http://it2810-03.idi.ntnu.no/project2/
## Core features

- **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.
- **My Matches:** Collects liked plants from both Plant Match and Explore Plants, with the same search, filters and match counts as Explore Plants. Both pages can also sort the plants by how well they match the user's preferences. 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. 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.
- **Walkthrough:** A short guide opens on the first visit and explains what the user can do on each page. It can be reopened at any time with the ? button, starts at the current page (or at the welcome step on the home page), links to each page and lets the user change language without closing it.

Expand Down
466 changes: 241 additions & 225 deletions backend/package-lock.json

Large diffs are not rendered by default.

57 changes: 43 additions & 14 deletions backend/src/queryBuilders.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { Document, Filter, ObjectId } from "mongodb";
import type {
ExplorePlantsArgs,
FilterCounts,
FilterParam,
PlantDoc,
PlantFilterArgs,
} from "./types.js";

// Helpers for searching, filtering and sorting plants
Expand All @@ -28,9 +28,32 @@ const rankOf = (order: string[], value: unknown): Document => ({
},
});

// Builds the aggregation stages that handle sorting
export const buildSortStages = (sort?: string): Document[] => {
// The preferences that exist, without duplicates. Unknown ones are left out.
export const knownPreferences = (preferences?: string[] | null): string[] =>
[...new Set(preferences ?? [])].filter((p) =>
Object.hasOwn(PREFERENCE_MATCHERS, p),
);

// The plants matching the most of the given preferences first, with the same
// score as Plant Match uses. Plants that match equally well are sorted by
// name. Without preferences, the plants are sorted by name.
const byPreferenceStages = (preferences: string[]): Document[] =>
preferences.length === 0
? [{ $sort: { commonName: 1, _id: 1 } }]
: [
{ $addFields: { matchScore: matchScore(preferences) } },
{ $sort: { matchScore: -1, commonName: 1, _id: 1 } },
];

// Builds the aggregation stages that handle sorting. preferences is only
// used by the "preferences" sort order.
export const buildSortStages = (
sort?: string,
preferences: string[] = [],
): Document[] => {
switch (sort) {
case "preferences":
return byPreferenceStages(preferences);
case "name_desc":
// _id is also reversed, so the sort can read the commonName index backwards
return [{ $sort: { commonName: -1, _id: -1 } }];
Expand Down Expand Up @@ -71,6 +94,7 @@ export const buildSortStages = (sort?: string): Document[] => {
export const buildMatchSortStages = (
sort: string | undefined,
matchedPlantIds: ObjectId[],
preferences: string[] = [],
): Document[] => {
const byMatchOrder = (direction: 1 | -1): Document[] => [
{
Expand All @@ -82,6 +106,8 @@ export const buildMatchSortStages = (
];

switch (sort) {
case "preferences":
return byPreferenceStages(preferences);
case "oldest":
return byMatchOrder(1);
case "name_asc":
Expand All @@ -95,10 +121,8 @@ export const buildMatchSortStages = (
}
};

// Builds the MongoDB filter for the search and filters on Explore Plants
export const buildExploreFilter = (
args: ExplorePlantsArgs,
): Filter<PlantDoc> => {
// Builds the MongoDB filter for the search and filters on Explore Plants and My Matches
export const buildPlantFilter = (args: PlantFilterArgs): Filter<PlantDoc> => {
const filter: Filter<PlantDoc> = {};
if (args.search?.trim()) {
const search = { $regex: escapeRegex(args.search.trim()), $options: "i" };
Expand All @@ -125,8 +149,8 @@ export const buildExploreFilter = (
return filter;
};

// The values each filter can have. Must match FILTERS in
// frontend/src/pages/explorePlants/ExplorePlantsPage.tsx
// The values each filter can have. Must match PLANT_FILTERS in
// frontend/src/components/plantSearchForm/plantFilters.ts
export const FILTER_OPTIONS: Record<FilterParam, string[]> = {
watering: ["minimum", "average", "frequent"],
sunlight: ["full_sun", "part_shade", "filtered_shade"],
Expand All @@ -138,22 +162,27 @@ 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
// search and the other filters stay. Uses buildPlantFilter, so the counts
// always agree with the results. All counts are done in one query.
export const buildFilterCountStages = (args: ExplorePlantsArgs): Document[] => {
// baseFilter limits which plants are counted at all, e.g. only the user's
// matches on My Matches. On Explore Plants every plant is counted.
export const buildFilterCountStages = (
args: PlantFilterArgs,
baseFilter: Filter<PlantDoc> = {},
): 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 }) },
{ $match: buildPlantFilter({ ...args, [param]: value }) },
{ $count: "count" },
];
}
}
return [
// Only the plants matching the search need to be looked at
{ $match: buildExploreFilter({ search: args.search }) },
// Only the plants matching the base filter and the search need to be looked at
{ $match: { ...baseFilter, ...buildPlantFilter({ search: args.search }) } },
{ $facet: facets },
];
};
Expand Down
124 changes: 70 additions & 54 deletions backend/src/resolvers.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import { GraphQLError } from "graphql";
import { ObjectId } from "mongodb";
import type { Document, WithId } from "mongodb";
import type { Document, Filter, WithId } from "mongodb";
import { db } from "./db.js";
import {
buildExploreFilter,
buildPlantFilter,
buildFilterCountStages,
buildMatchSortStages,
buildSortStages,
knownPreferences,
matchScore,
PREFERENCE_MATCHERS,
toFilterCounts,
} from "./queryBuilders.js";
import type {
ExplorePlantsArgs,
ExplorePage,
GetPlantsArgs,
MyMatchesArgs,
Plant,
PlantDoc,
PlantFilterArgs,
PlantPage,
UpdateUserPreferencesArgs,
UpdateUserProfileArgs,
User,
Expand Down Expand Up @@ -112,6 +114,42 @@ const cleanText = (
return trimmed || null;
};

// One page of plants for Explore Plants and My Matches: the plants matching the
// base filter (on My Matches the user's matches) and the user's search and
// filters, the total count, and the match counts for the filter values, so the
// frontend can show them and disable the values that would give no plants.
// The three queries run at the same time.
const findPlantPage = async (
baseFilter: Filter<PlantDoc>,
args: PlantFilterArgs & { limit?: number | null; offset?: number | null },
sortStages: Document[],
): Promise<PlantPage> => {
const filter = { ...baseFilter, ...buildPlantFilter(args) };

const [docs, totalCount, [facets]] = await Promise.all([
plants
.aggregate<WithId<PlantDoc>>([
{ $match: filter },
...sortStages,
{ $skip: clampOffset(args.offset) },
{ $limit: clampLimit(args.limit, DEFAULT_PAGE_SIZE) },
])
.toArray(),
plants.countDocuments(filter),
plants
.aggregate<Record<string, { count: number }[]>>(
buildFilterCountStages(args, baseFilter),
)
.toArray(),
]);

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

// Applies an update to one user and returns the updated user, or null if not found
const updateUser = async (
userId: string,
Expand All @@ -138,9 +176,7 @@ export const resolvers = {
const objectId = toObjectId(id);
return objectId ? [objectId] : [];
});
const preferences = [...new Set(args.preferences ?? [])].filter((p) =>
Object.hasOwn(PREFERENCE_MATCHERS, p),
);
const preferences = knownPreferences(args.preferences);

// Without preferences the plants come in random order. With preferences
// the best matches come first, and plants with the same score are shuffled.
Expand Down Expand Up @@ -184,34 +220,12 @@ export const resolvers = {
explorePlants: async (
_parent: unknown,
args: ExplorePlantsArgs,
): Promise<ExplorePage> => {
const filter = buildExploreFilter(args);

const [docs, totalCount, [facets]] = await Promise.all([
plants
.aggregate<WithId<PlantDoc>>([
{ $match: filter },
...buildSortStages(args.sort),
{ $skip: clampOffset(args.offset) },
{ $limit: clampLimit(args.limit, DEFAULT_PAGE_SIZE) },
])
.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,
filterCounts: toFilterCounts(facets),
};
},
): Promise<PlantPage> =>
findPlantPage(
{},
args,
buildSortStages(args.sort, knownPreferences(args.preferences)),
),

getUser: async (
_parent: unknown,
Expand All @@ -223,35 +237,37 @@ export const resolvers = {
return doc ? toUser(doc) : null;
},

// One page of the user's matched plants, sorted. Only the ids are stored on
// the user, so the plants are looked up and sorted in the plants collection.
// An unknown or malformed user id gives an empty page.
// One page of the user's matched plants, searched, filtered and sorted.
// Only the ids are stored on the user, so the plants are looked up and
// sorted in the plants collection. An unknown or malformed user id gives an
// empty page.
myMatches: async (
_parent: unknown,
args: MyMatchesArgs,
): Promise<{ plants: Plant[]; totalCount: number }> => {
): Promise<PlantPage> => {
const _id = toObjectId(args.userId);
const user = _id
? await users.findOne({ _id }, { projection: { matchedPlantIds: 1 } })
? await users.findOne(
{ _id },
{ projection: { matchedPlantIds: 1, preferences: 1 } },
)
: null;
const matchedPlantIds = user?.matchedPlantIds ?? [];
if (matchedPlantIds.length === 0) return { plants: [], totalCount: 0 };
if (matchedPlantIds.length === 0) {
return { plants: [], totalCount: 0, filterCounts: toFilterCounts() };
}

// Only plants that still exist are shown and counted (e.g. after a reseed)
const filter = { _id: { $in: matchedPlantIds } };
const [docs, totalCount] = await Promise.all([
plants
.aggregate<WithId<PlantDoc>>([
{ $match: filter },
...buildMatchSortStages(args.sort, matchedPlantIds),
{ $skip: clampOffset(args.offset) },
{ $limit: clampLimit(args.limit, DEFAULT_PAGE_SIZE) },
])
.toArray(),
plants.countDocuments(filter),
]);

return { plants: docs.map(toPlant), totalCount };
return findPlantPage(
{ _id: { $in: matchedPlantIds } },
args,
// The user's saved preferences, for the "preferences" sort order
buildMatchSortStages(
args.sort,
matchedPlantIds,
knownPreferences(user?.preferences),
),
);
},
},

Expand Down
14 changes: 7 additions & 7 deletions backend/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,17 @@ export const typeDefs = `
watering: String
careLevel: String
sort: String
preferences: [String!]
limit: Int = 12
offset: Int = 0
): ExplorePage!
): PlantPage!
getUser(userId: ID!): User
myMatches(
userId: ID!
search: String
sunlight: String
watering: String
careLevel: String
sort: String
limit: Int = 12
offset: Int = 0
Expand All @@ -33,11 +38,6 @@ export const typeDefs = `
removeUserMatch(userId: ID!, plantId: ID!): User
}
type PlantPage {
plants: [Plant!]!
totalCount: Int!
}
type OptionCount {
value: String!
count: Int!
Expand All @@ -49,7 +49,7 @@ export const typeDefs = `
careLevel: [OptionCount!]!
}
type ExplorePage {
type PlantPage {
plants: [Plant!]!
totalCount: Int!
filterCounts: FilterCounts!
Expand Down
Loading
Loading