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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,4 @@ and work practices.
## Known issues

TODO!
If you type and switch pages within half a second after updating your profile, the last few letters are not saved, because the debounce didn't have time to send.
2 changes: 1 addition & 1 deletion backend/.env.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
MONGODB_URI=mongodb://localhost:27017
DB_NAME=plants
DB_NAME=iloveplants
PERENUAL_API_KEY=
PORT=3001
2 changes: 1 addition & 1 deletion backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ Da er DB koblingen satt opp riktig
Kjør med SSH-tunnelen oppe og `PERENUAL_API_KEY` satt i `.env`:

```bash
npm run seed:reset # sletter HELE databasen og laster alt inn på nytt
npm run seed:reset # sletter plante databasen og laster alt inn på nytt
npm run seed # fyller bare inn det som mangler
```

Expand Down
7 changes: 0 additions & 7 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 1 addition & 3 deletions backend/seedDataFetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,14 +254,12 @@ async function fetchPlantDetails() {
}
}

// ---------- Kjøring ----------

try {
// Sjekk nøkkelen før noe slettes, ellers står vi igjen med en tom database
if (!API_KEY) throw new Error("PERENUAL_API_KEY mangler i .env");
if (RESET) {
console.log(`Sletter hele databasen "${db.databaseName}"...`);
await db.dropDatabase();
await plants.drop();
}
await plants.createIndex({ perenualId: 1 }, { unique: true });
await fetchPlantList();
Expand Down
2 changes: 1 addition & 1 deletion backend/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ export const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();
console.log("Connected to MongoDB");

export const db = client.db(process.env.DB_NAME ?? "plants");
export const db = client.db(process.env.DB_NAME ?? "iloveplants");
248 changes: 247 additions & 1 deletion backend/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
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 (only the fields we read)
// The shape of a plant document in MongoDB
interface PlantDoc {
commonName: string;
// Base64-encoded Perenual image as a data URI, stored by seedDataFetch.js
Expand Down Expand Up @@ -43,7 +45,79 @@ interface ExplorePlantsArgs {
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
const PROFILE_PICTURES = [
"default",
"monstera",
"pothos",
"snake-plant",
"anthurium",
"succulent",
"fern",
"orchid",
];

// 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 typeDefs = `
type Query{
Expand All @@ -57,6 +131,20 @@ const typeDefs = `
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 {
Expand All @@ -74,6 +162,16 @@ const typeDefs = `
sunlight: [String]
careLevel: String
}
type User {
id: ID!
name: String
description: String
profilePicture: String!
preferences: [String!]!
matchedPlants: [Plant!]!
createdAt: String!
}
`;

const toPlant = (doc: WithId<PlantDoc>): Plant => ({
Expand All @@ -87,6 +185,49 @@ const toPlant = (doc: WithId<PlantDoc>): Plant => ({
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;
};

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

Expand Down Expand Up @@ -211,6 +352,111 @@ const resolvers = {

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)] : [];
});
},
},
};

Expand Down
2 changes: 2 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Architecture

TODO: updated with new arciture

This document describes how the data flows from the API to the frontend, how the frontend, backend and database fit together. It also describes the plant data and the Perenual API and why we chose GraphQL and MongoDB.
The folder structure is shown at the end of this document.

Expand Down
Loading
Loading