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
Binary file removed backend/.DS_Store
Binary file not shown.
92 changes: 92 additions & 0 deletions backend/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import type { Document, Filter } from "mongodb";
import type { ExplorePlantsArgs, PlantDoc } from "./types.js";

// Helpers for searching, filtering and sorting plants

// Escape user input so it can't be interpreted as regex
export const escapeRegex = (s: string) =>
s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

// Filter values come in as "full_sun", the database has "full sun"
export const normalize = (s: string) =>
escapeRegex(s.replace(/_/g, " ").trim());

// Order from low to high.
export const SORT_ORDERS = {
watering: ["minimum", "average", "frequent"],
careLevel: ["low", "medium", "high"],
};

// Position in the order list, unknown or missing values go last
export const rankOf = (order: string[], value: unknown): Document => ({
$let: {
vars: { i: { $indexOfArray: [order, value] } },
in: { $cond: [{ $lt: ["$$i", 0] }, 999, "$$i"] },
},
});

// Builds the aggregation stages that handle sorting
export const buildSortStages = (sort?: string): Document[] => {
switch (sort) {
case "name_desc":
return [{ $sort: { commonName: -1, _id: 1 } }];
case "watering_asc":
return [
{
$addFields: {
sortRank: rankOf(SORT_ORDERS.watering, { $toLower: "$watering" }),
},
},
{ $sort: { sortRank: 1, commonName: 1, _id: 1 } },
];
case "careLevel_asc":
// "Moderate" and "Medium" both exist in the data, treat them as equal
return [
{
$addFields: {
sortRank: rankOf(SORT_ORDERS.careLevel, {
$let: {
vars: { c: { $toLower: { $ifNull: ["$careLevel", ""] } } },
in: {
$cond: [{ $eq: ["$$c", "moderate"] }, "medium", "$$c"],
},
},
}),
},
},
{ $sort: { sortRank: 1, commonName: 1, _id: 1 } },
];
default:
return [{ $sort: { commonName: 1, _id: 1 } }];
}
};

// Builds the MongoDB filter for the search and filters on Explore Plants
export const buildExploreFilter = (
args: ExplorePlantsArgs,
): Filter<PlantDoc> => {
const filter: Filter<PlantDoc> = {};
if (args.search?.trim()) {
filter.commonName = {
$regex: escapeRegex(args.search.trim()),
$options: "i",
};
}
if (args.watering) {
filter.watering = new RegExp(`^${normalize(args.watering)}$`, "i");
}
if (args.sunlight) {
// sunlight is a list, and a value can be combined, e.g. "part sun/part shade".
// A regex on a list matches if any of the values contain the filter.
filter.sunlight = new RegExp(normalize(args.sunlight), "i");
}
if (args.careLevel) {
const level = normalize(args.careLevel);
// "Medium" and "Moderate" both exist in the data and mean the same
filter.careLevel = new RegExp(
level === "medium" ? "^(medium|moderate)$" : `^${level}$`,
"i",
);
}
return filter;
};
269 changes: 269 additions & 0 deletions backend/src/resolvers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,269 @@
import { GraphQLError } from "graphql";
import { ObjectId } from "mongodb";
import type { Document, WithId } from "mongodb";
import { db } from "./db.js";
import { buildExploreFilter, buildSortStages } from "./helpers.js";
import type {
ExplorePlantsArgs,
GetPlantsArgs,
Plant,
PlantDoc,
UpdateUserPreferencesArgs,
UpdateUserProfileArgs,
User,
UserDoc,
UserIdArgs,
UserMatchArgs,
} from "./types.js";

// Same limits as the inputs on the profile page
const NAME_MAX_LENGTH = 40;
const DESCRIPTION_MAX_LENGTH = 100;

// Must match the avatar ids in frontend/src/pages/profile/Profile.tsx and the
// result ids in frontend/src/pages/plantOwnerTest/plantownertest.ts
const PROFILE_PICTURES = [
"default",
"monstera",
"pothos",
"snake-plant",
"anthurium",
"succulent",
"fern",
"orchid",
// Results from the plant owner test
"cityMinimalist",
"averageCityGardener",
"cityGardenerDreaming",
"countryMinimalist",
"averageCountryGardener",
"gardenExpert",
];

// Must match the preference ids in frontend/src/pages/profile/Profile.tsx
const PREFERENCES = [
"minimumWater",
"averageWater",
"frequentWater",
"fullSun",
"partShade",
"filteredShade",
"easyCare",
"mediumCare",
"hardCare",
];

const plants = db.collection<PlantDoc>("plants");
const users = db.collection<UserDoc>("users");

const toPlant = (doc: WithId<PlantDoc>): Plant => ({
id: doc._id.toString(),
name: doc.commonName,
imageURL: doc.imageData ?? doc.imageURL ?? null,
scientificName: doc.scientificName,
description: doc.description,
watering: doc.watering,
sunlight: doc.sunlight,
careLevel: doc.careLevel,
});

const toUser = (doc: WithId<UserDoc>): User => ({
id: doc._id.toString(),
name: doc.name,
description: doc.description,
profilePicture: doc.profilePicture,
preferences: doc.preferences,
matchedPlantIds: doc.matchedPlantIds,
createdAt: doc.createdAt.toISOString(),
});

const badInput = (message: string) =>
new GraphQLError(message, { extensions: { code: "BAD_USER_INPUT" } });

// Ids come from the client, so a malformed id gives null instead of a crash
const toObjectId = (id: string): ObjectId | null =>
ObjectId.isValid(id) ? new ObjectId(id) : null;

// Trims text and checks the length. Empty text is stored as null.
const cleanText = (
value: string | null | undefined,
maxLength: number,
field: string,
): string | null => {
const trimmed = value?.trim() ?? "";
if (trimmed.length > maxLength) {
throw badInput(`${field} can be at most ${maxLength} characters`);
}
return trimmed || null;
};

// Applies an update to one user and returns the updated user, or null if not found
const updateUser = async (
userId: string,
update: Document,
): Promise<User | null> => {
const _id = toObjectId(userId);
if (!_id) return null;
const doc = await users.findOneAndUpdate({ _id }, update, {
returnDocument: "after",
});
return doc ? toUser(doc) : null;
};

export const resolvers = {
Query: {
getPlants: async (
_parent: unknown,
args: GetPlantsArgs,
): Promise<Plant[]> => {
const docs = await plants
.aggregate<WithId<PlantDoc>>([
{
$sample: {
size: args.limit,
},
},
{
$project: {
commonName: 1,
imageData: 1,
imageURL: 1,
scientificName: 1,
description: 1,
watering: 1,
sunlight: 1,
careLevel: 1,
},
},
])
.toArray();
return docs.map(toPlant);
},

explorePlants: async (
_parent: unknown,
args: ExplorePlantsArgs,
): Promise<{ plants: Plant[]; totalCount: number }> => {
const filter = buildExploreFilter(args);

const [docs, totalCount] = await Promise.all([
plants
.aggregate<WithId<PlantDoc>>([
{ $match: filter },
...buildSortStages(args.sort),
{ $skip: args.offset },
{ $limit: args.limit },
])
.toArray(),
plants.countDocuments(filter),
]);

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

getUser: async (
_parent: unknown,
args: UserIdArgs,
): Promise<User | null> => {
const _id = toObjectId(args.userId);
if (!_id) return null;
const doc = await users.findOne({ _id });
return doc ? toUser(doc) : null;
},
},

Mutation: {
createUser: async (): Promise<User> => {
const doc: UserDoc = {
name: null,
description: null,
profilePicture: "default",
preferences: [],
matchedPlantIds: [],
createdAt: new Date(),
};
const { insertedId } = await users.insertOne(doc);
return toUser({ _id: insertedId, ...doc });
},

updateUserProfile: async (
_parent: unknown,
args: UpdateUserProfileArgs,
): Promise<User | null> => {
// Only fields that were sent are changed
const changes: Partial<UserDoc> = {};
if (args.name !== undefined) {
changes.name = cleanText(args.name, NAME_MAX_LENGTH, "Name");
}
if (args.description !== undefined) {
changes.description = cleanText(
args.description,
DESCRIPTION_MAX_LENGTH,
"Description",
);
}
if (args.profilePicture !== undefined) {
const picture = args.profilePicture ?? "default";
if (!PROFILE_PICTURES.includes(picture)) {
throw badInput(`Unknown profile picture: ${picture}`);
}
changes.profilePicture = picture;
}
return updateUser(args.userId, { $set: changes });
},

updateUserPreferences: async (
_parent: unknown,
args: UpdateUserPreferencesArgs,
): Promise<User | null> => {
const unknown = args.preferences.filter((p) => !PREFERENCES.includes(p));
if (unknown.length > 0) {
throw badInput(`Unknown preferences: ${unknown.join(", ")}`);
}
// Set removes duplicates
const preferences = [...new Set(args.preferences)];
return updateUser(args.userId, { $set: { preferences } });
},

addUserMatch: async (
_parent: unknown,
args: UserMatchArgs,
): Promise<User | null> => {
const plantId = toObjectId(args.plantId);
if (!plantId || !(await plants.countDocuments({ _id: plantId }))) {
throw badInput(`Unknown plant: ${args.plantId}`);
}
// $addToSet never adds the same plant twice
return updateUser(args.userId, {
$addToSet: { matchedPlantIds: plantId },
});
},

removeUserMatch: async (
_parent: unknown,
args: UserMatchArgs,
): Promise<User | null> => {
const plantId = toObjectId(args.plantId);
if (!plantId) throw badInput(`Unknown plant: ${args.plantId}`);
return updateUser(args.userId, {
$pull: { matchedPlantIds: plantId },
});
},
},

User: {
// Looks up the matched plants, in the order they were matched.
// Ids of plants that no longer exist (e.g. after a reseed) are skipped.
matchedPlants: async (user: User): Promise<Plant[]> => {
if (user.matchedPlantIds.length === 0) return [];
const docs = await plants
.find({ _id: { $in: user.matchedPlantIds } })
.toArray();
const byId = new Map(docs.map((doc) => [doc._id.toString(), doc]));
return user.matchedPlantIds.flatMap((id) => {
const doc = byId.get(id.toString());
return doc ? [toPlant(doc)] : [];
});
},
},
};
Loading
Loading