From 61d55b34afe4178777a19c2dabe063d485424997 Mon Sep 17 00:00:00 2001 From: ninaflaaten Date: Thu, 5 Nov 2026 15:59:44 +0100 Subject: [PATCH] Split server.ts into separate files --- backend/.DS_Store | Bin 8196 -> 0 bytes backend/src/helpers.ts | 92 ++++++++ backend/src/resolvers.ts | 269 ++++++++++++++++++++++ backend/src/schema.ts | 55 +++++ backend/src/server.ts | 474 +-------------------------------------- backend/src/types.ts | 83 +++++++ docs/architecture.md | 14 +- 7 files changed, 512 insertions(+), 475 deletions(-) delete mode 100644 backend/.DS_Store create mode 100644 backend/src/helpers.ts create mode 100644 backend/src/resolvers.ts create mode 100644 backend/src/schema.ts create mode 100644 backend/src/types.ts diff --git a/backend/.DS_Store b/backend/.DS_Store deleted file mode 100644 index ba02b014d9b3fc1148f0e5c0774fed72bfb7b4ff..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8196 zcmeHMyKWOf6usjFSd#?SV26M}THywX03it=giwqL4?~eCjv(P>*6WG0$$G}xUB`qd zl53Fo018SzfQpial9qyoAE2P3g*y)i+aU!F0x@IFoVzpk+}Szy?D*OMK=O^sS%47$ zu&@fW2eA1?5#yq6D+%3`L?p-uC_xQ4RGBgcDq zHb$rTs=zeP9b>(YS251L3^GRdyb1BJ=)ChjR6xlDmSCLR^e^A9{5o_ zHujMu`ucb6-ec{t2CRq0W!@~tZrq6SZg^i@&2t`<+qPT2gW5lUQ$X|2GPIL^3+^3K%7 zP;`fe5#lz^!lE07F00b~`oq92(_n_>c^vba@D$N-A+sSBk>uRPy6gF@nw|QpM9k)9 z+r|lH*pO8QeuGZ8EsZ4muGW(FJmZWeliA#DJ!HX2xB|DJh#%D^ynvVR8s5Tt_yk|z z8|f#* z{~ubBxmBZpQQ&tKApO(D={&OJss0PLIOQFzkFkm({8|bn1)Huf0(iakhauVyx(ZHC VV@o0SU@<=gNEu9H6!@bG`~ZJTA?*MF diff --git a/backend/src/helpers.ts b/backend/src/helpers.ts new file mode 100644 index 00000000..71c41a81 --- /dev/null +++ b/backend/src/helpers.ts @@ -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 => { + const filter: Filter = {}; + 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; +}; diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts new file mode 100644 index 00000000..2a9c06e6 --- /dev/null +++ b/backend/src/resolvers.ts @@ -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("plants"); +const users = db.collection("users"); + +const toPlant = (doc: WithId): 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): 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 => { + 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 => { + const docs = await plants + .aggregate>([ + { + $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>([ + { $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 => { + const _id = toObjectId(args.userId); + if (!_id) return null; + const doc = await users.findOne({ _id }); + return doc ? toUser(doc) : null; + }, + }, + + Mutation: { + createUser: async (): Promise => { + 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 => { + // Only fields that were sent are changed + const changes: Partial = {}; + 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 => { + 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 => { + 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 => { + 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 => { + 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)] : []; + }); + }, + }, +}; diff --git a/backend/src/schema.ts b/backend/src/schema.ts new file mode 100644 index 00000000..7971be29 --- /dev/null +++ b/backend/src/schema.ts @@ -0,0 +1,55 @@ +// The GraphQL schema. The resolvers are in resolvers.ts. +export const typeDefs = ` + type Query{ + getPlants(limit: Int = 50, offset: Int = 0): [Plant] + explorePlants( + search: String + sunlight: String + watering: String + careLevel: String + sort: String + limit: Int = 12 + offset: Int = 0 + ): PlantPage! + getUser(userId: ID!): User + } + + type Mutation { + createUser: User! + updateUserProfile( + userId: ID! + name: String + description: String + profilePicture: String + ): User + updateUserPreferences(userId: ID!, preferences: [String!]!): User + addUserMatch(userId: ID!, plantId: ID!): User + removeUserMatch(userId: ID!, plantId: ID!): User + } + + type PlantPage { + plants: [Plant!]! + totalCount: Int! + } + + type Plant{ + id: ID! + name: String! + imageURL: String + scientificName: [String] + description: String + watering: String + sunlight: [String] + careLevel: String + } + + type User { + id: ID! + name: String + description: String + profilePicture: String! + preferences: [String!]! + matchedPlants: [Plant!]! + createdAt: String! + } +`; diff --git a/backend/src/server.ts b/backend/src/server.ts index 99a33ee7..491f31c9 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -1,477 +1,7 @@ import { ApolloServer } from "@apollo/server"; import { startStandaloneServer } from "@apollo/server/standalone"; -import { GraphQLError } from "graphql"; -import { ObjectId } from "mongodb"; -import type { Document, Filter, WithId } from "mongodb"; -import { db } from "./db.js"; - -// The shape of a plant document in MongoDB -interface PlantDoc { - commonName: string; - // Base64-encoded Perenual image as a data URI, stored by seedDataFetch.js - imageData?: string | null; - imageURL?: string | null; - scientificName?: string[]; - description?: string; - watering?: string; - sunlight?: string[]; - careLevel?: string; -} - -// The shape of a Plant in the GraphQL API -interface Plant { - id: string; - name: string; - imageURL: string | null; - scientificName?: string[]; - description?: string; - watering?: string; - sunlight?: string[]; - careLevel?: string; -} - -interface GetPlantsArgs { - limit: number; - offset: number; -} - -interface ExplorePlantsArgs { - search?: string; - sunlight?: string; - watering?: string; - careLevel?: string; - sort?: string; - limit?: number; - offset?: number; -} - -// The shape of a user document in MongoDB. _id is added by MongoDB. -interface UserDoc { - // null means the user has not chosen one, the frontend shows a translated default - name: string | null; - description: string | null; - profilePicture: string; - preferences: string[]; - // Only the plant ids are stored, the plants are looked up in User.matchedPlants - matchedPlantIds: ObjectId[]; - createdAt: Date; -} - -// The shape of a User in the GraphQL API. matchedPlantIds is not in the schema, -// it is only passed on to the User.matchedPlants resolver. -interface User { - id: string; - name: string | null; - description: string | null; - profilePicture: string; - preferences: string[]; - matchedPlantIds: ObjectId[]; - createdAt: string; -} - -interface UserIdArgs { - userId: string; -} - -interface UpdateUserProfileArgs extends UserIdArgs { - name?: string | null; - description?: string | null; - profilePicture?: string | null; -} - -interface UpdateUserPreferencesArgs extends UserIdArgs { - preferences: string[]; -} - -interface UserMatchArgs extends UserIdArgs { - plantId: string; -} - -// 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("plants"); -const users = db.collection("users"); - -const typeDefs = ` - type Query{ - getPlants(limit: Int = 50, offset: Int = 0): [Plant] - explorePlants( - search: String - sunlight: String - watering: String - careLevel: String - sort: String - limit: Int = 12 - offset: Int = 0 - ): PlantPage! - getUser(userId: ID!): User - } - - type Mutation { - createUser: User! - updateUserProfile( - userId: ID! - name: String - description: String - profilePicture: String - ): User - updateUserPreferences(userId: ID!, preferences: [String!]!): User - addUserMatch(userId: ID!, plantId: ID!): User - removeUserMatch(userId: ID!, plantId: ID!): User - } - - type PlantPage { - plants: [Plant!]! - totalCount: Int! - } - - type Plant{ - id: ID! - name: String! - imageURL: String - scientificName: [String] - description: String - watering: String - sunlight: [String] - careLevel: String - } - - type User { - id: ID! - name: String - description: String - profilePicture: String! - preferences: [String!]! - matchedPlants: [Plant!]! - createdAt: String! - } -`; - -const toPlant = (doc: WithId): 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): 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 => { - const _id = toObjectId(userId); - if (!_id) return null; - const doc = await users.findOneAndUpdate({ _id }, update, { - returnDocument: "after", - }); - return doc ? toUser(doc) : null; -}; - -// Escape user input so it can't be interpreted as regex -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"], -}; - -// Position in the order list, unknown or missing values go last -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 -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 } }]; - } -}; - -const resolvers = { - Query: { - getPlants: async ( - _parent: unknown, - args: GetPlantsArgs, - ): Promise => { - const docs = await plants - .aggregate>([ - { - $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: Filter = {}; - - 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", - ); - } - - const [docs, totalCount] = await Promise.all([ - plants - .aggregate>([ - { $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 => { - const _id = toObjectId(args.userId); - if (!_id) return null; - const doc = await users.findOne({ _id }); - return doc ? toUser(doc) : null; - }, - }, - - Mutation: { - createUser: async (): Promise => { - 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 => { - // Only fields that were sent are changed - const changes: Partial = {}; - 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 => { - 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 => { - 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 => { - 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 => { - 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)] : []; - }); - }, - }, -}; +import { resolvers } from "./resolvers.js"; +import { typeDefs } from "./schema.js"; const server = new ApolloServer({ typeDefs, resolvers }); diff --git a/backend/src/types.ts b/backend/src/types.ts new file mode 100644 index 00000000..4cba72f3 --- /dev/null +++ b/backend/src/types.ts @@ -0,0 +1,83 @@ +import type { ObjectId } from "mongodb"; + +// The shape of a plant document in MongoDB +export interface PlantDoc { + commonName: string; + // Base64-encoded Perenual image as a data URI, stored by seedDataFetch.js + imageData?: string | null; + imageURL?: string | null; + scientificName?: string[]; + description?: string; + watering?: string; + sunlight?: string[]; + careLevel?: string; +} + +// The shape of a Plant in the GraphQL API +export interface Plant { + id: string; + name: string; + imageURL: string | null; + scientificName?: string[]; + description?: string; + watering?: string; + sunlight?: string[]; + careLevel?: string; +} + +export interface GetPlantsArgs { + limit: number; + offset: number; +} + +export interface ExplorePlantsArgs { + search?: string; + sunlight?: string; + watering?: string; + careLevel?: string; + sort?: string; + limit?: number; + offset?: number; +} + +// 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 + name: string | null; + description: string | null; + profilePicture: string; + preferences: string[]; + // Only the plant ids are stored, the plants are looked up in User.matchedPlants + matchedPlantIds: ObjectId[]; + createdAt: Date; +} + +// The shape of a User in the GraphQL API. matchedPlantIds is not in the schema, +// it is only passed on to the User.matchedPlants resolver. +export interface User { + id: string; + name: string | null; + description: string | null; + profilePicture: string; + preferences: string[]; + matchedPlantIds: ObjectId[]; + createdAt: string; +} + +export interface UserIdArgs { + userId: string; +} + +export interface UpdateUserProfileArgs extends UserIdArgs { + name?: string | null; + description?: string | null; + profilePicture?: string | null; +} + +export interface UpdateUserPreferencesArgs extends UserIdArgs { + preferences: string[]; +} + +export interface UserMatchArgs extends UserIdArgs { + plantId: string; +} diff --git a/docs/architecture.md b/docs/architecture.md index efbe3d50..4281db03 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -62,7 +62,11 @@ All user queries and mutations ask for the same `UserFields` fragment, so when o The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks for exactly the fields each view needs. A plant card needs more fields than a list item, and both are served by the same `Plant` type without extra endpoints. The schema also gives us one typed contract between frontend and backend. - `db.ts` connects to MongoDB using `MONGODB_URI` and `DB_NAME` from `.env` (see `.env.example`). The database name defaults to `iloveplants`. -- `server.ts` defines the schema and resolvers, and starts Apollo Server on `PORT` (default 3001). +- `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. +- `helpers.ts` builds the MongoDB filters and sort stages for searching, filtering and sorting plants. +- `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). ### Schema @@ -150,7 +154,7 @@ One document per user. There is no login: a user is created the first time someo | `matchedPlantIds` | ObjectId[] | `_id`s of the plants the user has matched with, in the order they were matched | `matchedPlants` (resolved to full `Plant` objects) | | `createdAt` | Date | When the user was created | `createdAt` (ISO string) | -A new user starts with `name: null`, `description: null`, `profilePicture: "default"`, and empty `preferences` and `matchedPlantIds`. The allowed picture and preference ids are listed in `server.ts` and must match the ids used in the frontend (`Profile.tsx` and `plantownertest.ts`). +A new user starts with `name: null`, `description: null`, `profilePicture: "default"`, and empty `preferences` and `matchedPlantIds`. The allowed picture and preference ids are listed in `resolvers.ts` and must match the ids used in the frontend (`Profile.tsx` and `plantownertest.ts`). Matches only store the plant id, not a copy of the plant. That keeps user documents small and means the user always sees the current plant data. @@ -215,7 +219,11 @@ T03-Project-2/ ├── backend/ │ ├── src/ │ │ ├── db.ts # MongoDB connection (MongoDB driver, configured via .env) -│ │ └── server.ts # Apollo Server with GraphQL schema and resolvers for plants and users +│ │ ├── helpers.ts # Filters and sort stages for searching, filtering and sorting plants +│ │ ├── resolvers.ts # GraphQL resolvers for plants and users +│ │ ├── schema.ts # GraphQL schema +│ │ ├── server.ts # Starts Apollo Server +│ │ └── types.ts # TypeScript types for documents, GraphQL types and arguments │ ├── tests/ # Backend tests against an in-memory MongoDB (db, server) │ ├── seedDataFetch.js # Script that fetches plant data from the Perenual API and stores it in MongoDB │ └── .env.example # Template for required environment variables