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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,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.
- **Plant Match:** The user swipes the card right to match with a plant and left to skip it, or uses the ♥ and ✖ buttons. 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, 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.
- **Plant Owner Test:** Four questions give one of six plant owner types, whose picture can be used as profile picture. The result also suggests one preference each for watering, light and care level, based on the answers and the description of the type. The user chooses which of them to add, and they are added to the preferences they already have, so PlantMatch puts plants that suit them first right away.
Expand Down
15 changes: 15 additions & 0 deletions backend/src/migrations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { Db } from "mongodb";

// Updates data stored by older versions of the app. Each step only changes
// documents that still have the old value, so this is safe to run every time
// the server starts.
export async function migrateData(database: Db) {
// The snake plant avatar id was "snake-plant". It is now "snakePlant", in
// the same camelCase as the other picture ids.
await database
.collection("users")
.updateMany(
{ profilePicture: "snake-plant" },
{ $set: { profilePicture: "snakePlant" } },
);
}
29 changes: 15 additions & 14 deletions backend/src/queryBuilders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,9 @@ const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Filter values come in as "full_sun", the database has "full sun"
const normalize = (s: string) => escapeRegex(s.replace(/_/g, " ").trim());

// Order from low to high.
const SORT_ORDERS = {
watering: ["minimum", "average", "frequent"],
careLevel: ["low", "medium", "high"],
};
// Sorted by name A–Z, with _id as a tie-breaker so the order is stable.
// Uses the index from indexes.ts.
const BY_NAME = { commonName: 1, _id: 1 } as const;

// Position in the order list, unknown or missing values go last
const rankOf = (order: string[], value: unknown): Document => ({
Expand All @@ -39,10 +37,10 @@ export const knownPreferences = (preferences?: string[] | null): string[] =>
// name. Without preferences, the plants are sorted by name.
const byPreferenceStages = (preferences: string[]): Document[] =>
preferences.length === 0
? [{ $sort: { commonName: 1, _id: 1 } }]
? [{ $sort: BY_NAME }]
: [
{ $addFields: { matchScore: matchScore(preferences) } },
{ $sort: { matchScore: -1, commonName: 1, _id: 1 } },
{ $sort: { matchScore: -1, ...BY_NAME } },
];

// Builds the aggregation stages that handle sorting. preferences is only
Expand All @@ -61,17 +59,19 @@ export const buildSortStages = (
return [
{
$addFields: {
sortRank: rankOf(SORT_ORDERS.watering, { $toLower: "$watering" }),
sortRank: rankOf(FILTER_OPTIONS.watering, {
$toLower: "$watering",
}),
},
},
{ $sort: { sortRank: 1, commonName: 1, _id: 1 } },
{ $sort: { sortRank: 1, ...BY_NAME } },
];
case "careLevel_asc":
// "Moderate" and "Medium" both exist in the data, treat them as equal
return [
{
$addFields: {
sortRank: rankOf(SORT_ORDERS.careLevel, {
sortRank: rankOf(FILTER_OPTIONS.careLevel, {
$let: {
vars: { c: { $toLower: { $ifNull: ["$careLevel", ""] } } },
in: {
Expand All @@ -81,10 +81,10 @@ export const buildSortStages = (
}),
},
},
{ $sort: { sortRank: 1, commonName: 1, _id: 1 } },
{ $sort: { sortRank: 1, ...BY_NAME } },
];
default:
return [{ $sort: { commonName: 1, _id: 1 } }];
return [{ $sort: BY_NAME }];
}
};

Expand All @@ -111,7 +111,7 @@ export const buildMatchSortStages = (
case "oldest":
return byMatchOrder(1);
case "name_asc":
return [{ $sort: { commonName: 1, _id: 1 } }];
return [{ $sort: BY_NAME }];
case "name_desc":
return [{ $sort: { commonName: -1, _id: -1 } }];
default:
Expand Down Expand Up @@ -149,7 +149,8 @@ export const buildPlantFilter = (args: PlantFilterArgs): Filter<PlantDoc> => {
return filter;
};

// The values each filter can have. Must match PLANT_FILTERS in
// The values each filter can have, from low to high, so the watering and
// care level sort orders use them too. Must match PLANT_FILTERS in
// frontend/src/components/plantSearchForm/plantFilters.ts
export const FILTER_OPTIONS: Record<FilterParam, string[]> = {
watering: ["minimum", "average", "frequent"],
Expand Down
5 changes: 3 additions & 2 deletions backend/src/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type {
ExplorePlantsArgs,
GetPlantsArgs,
MyMatchesArgs,
PaginationArgs,
Plant,
PlantDoc,
PlantFilterArgs,
Expand All @@ -38,7 +39,7 @@ const PROFILE_PICTURES = [
"default",
"monstera",
"pothos",
"snake-plant",
"snakePlant",
"anthurium",
"succulent",
"fern",
Expand Down Expand Up @@ -121,7 +122,7 @@ const cleanText = (
// The three queries run at the same time.
const findPlantPage = async (
baseFilter: Filter<PlantDoc>,
args: PlantFilterArgs & { limit?: number | null; offset?: number | null },
args: PlantFilterArgs & PaginationArgs,
sortStages: Document[],
): Promise<PlantPage> => {
const filter = { ...baseFilter, ...buildPlantFilter(args) };
Expand Down
4 changes: 2 additions & 2 deletions backend/src/schema.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// The GraphQL schema. The resolvers are in resolvers.ts.
export const typeDefs = `
type Query{
type Query {
getPlants(limit: Int = 50, excludeIds: [ID!], preferences: [String!]): [Plant]
explorePlants(
search: String
Expand Down Expand Up @@ -55,7 +55,7 @@ export const typeDefs = `
filterCounts: FilterCounts!
}
type Plant{
type Plant {
id: ID!
name: String!
imageURL: String
Expand Down
5 changes: 4 additions & 1 deletion backend/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import { resolvers } from "./resolvers.js";
import { typeDefs } from "./schema.js";
import { db } from "./db.js";
import { ensureIndexes } from "./indexes.js";
import { migrateData } from "./migrations.js";

// Create the database indexes before the server starts taking requests
// Create the database indexes and update old data before the server starts
// taking requests
await ensureIndexes(db);
await migrateData(db);

const server = new ApolloServer({ typeDefs, resolvers });

Expand Down
18 changes: 10 additions & 8 deletions backend/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,18 @@ export interface PlantFilterArgs {
careLevel?: string | null;
}

export interface ExplorePlantsArgs extends PlantFilterArgs {
// The sort order and page, on Explore Plants and My Matches.
// Null if the client sends null explicitly, see clampLimit in resolvers.ts
export interface PaginationArgs {
sort?: string;
limit?: number | null;
offset?: number | null;
}

export interface ExplorePlantsArgs extends PlantFilterArgs, PaginationArgs {
// The user's preferences, for the "preferences" sort order. Explore Plants
// has no user id, so the frontend sends them, like for getPlants.
preferences?: string[] | null;
limit?: number | null;
offset?: number | null;
}

// The filters on Explore Plants and My Matches
Expand Down Expand Up @@ -114,8 +119,5 @@ export interface UserMatchArgs extends UserIdArgs {
plantId: string;
}

export interface MyMatchesArgs extends UserIdArgs, PlantFilterArgs {
sort?: string;
limit?: number | null;
offset?: number | null;
}
export interface MyMatchesArgs
extends UserIdArgs, PlantFilterArgs, PaginationArgs {}
28 changes: 28 additions & 0 deletions backend/tests/migrations.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { MongoClient } from "mongodb";
import { afterAll, expect, inject, it } from "vitest";
import { migrateData } from "../src/migrations.js";

// Uses the in-memory MongoDB from globalSetup.ts, with its own database for this file
const client = await MongoClient.connect(inject("mongoUri"));
const db = client.db("migrations-test");

afterAll(async () => {
await client.close();
});

it("renames the old snake-plant avatar id, and can run again on the next start", async () => {
const users = db.collection("users");
await users.insertMany([
{ name: "old", profilePicture: "snake-plant" },
{ name: "other", profilePicture: "fern" },
]);

await migrateData(db);
// The server runs this on every start, so running it twice must not fail
await migrateData(db);

const pictures = (await users.find().sort({ name: 1 }).toArray()).map(
(user) => user.profilePicture,
);
expect(pictures).toEqual(["snakePlant", "fern"]);
});
Loading
Loading