Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Deps] Update to Mongoose 6 #170

Merged
merged 10 commits into from
Jun 15, 2024
279 changes: 43 additions & 236 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@
"lusca": "^1.7.0",
"markdown-it": "^14.1.0",
"markdown-it-texmath": "^1.0.0",
"mongoose": "^5.13.20",
"mongodb": "^4.17.2",
"mongoose": "^6.13.0",
"nodemailer": "^6.9.9",
"path": "0.12.7",
"sjcl": "1.0.7",
Expand Down
12 changes: 8 additions & 4 deletions src/models/CardsMongoDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* @module
*/

import { FilterQuery } from "mongoose";
import { FilterQuery, SortOrder } from "mongoose";
import { BaseResponse } from "../types";
import * as MetadataDB from "./MetadataMongoDB";
import { Card, ICard, ICardRaw } from "./mongoose_models/CardSchema";
Expand Down Expand Up @@ -81,7 +81,7 @@ export function read(
"title description descriptionHTML tags urgency createdById isPublic",
): Promise<ICardRaw | null> {
payload = sanitizeQuery(payload);
const query: Partial<ICard> = { createdById: payload.userIDInApp };
const query: FilterQuery<ICard> = { createdById: payload.userIDInApp };
if (payload.cardID) { query._id = payload.cardID; }
return Card.findOne(query).select(projection).exec();
}
Expand Down Expand Up @@ -135,11 +135,15 @@ interface ServerAddedSearchCardParams {
isPublic?: boolean;
}

interface SortCriteria {
[key: string]: SortOrder | { $meta: "textScore" };
}

interface CardQuery {
filter: FilterQuery<ICard>;
projection: string;
limit: number;
sortCriteria: object;
sortCriteria: SortCriteria;
}

const kCardsSearchProjection = "title tags urgency";
Expand Down Expand Up @@ -234,7 +238,7 @@ function computeInternalQueryFromClientQuery(
mandatoryFields.push({ createdAt: dateQuery });
}

const sortCriteria = clientQuery.queryString
const sortCriteria: SortCriteria = clientQuery.queryString
? { score: { $meta: "textScore" } }
: {};

Expand Down
33 changes: 19 additions & 14 deletions src/models/DailyTasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,28 @@

import * as mongoDB from "mongodb";

import { FilterQuery, UpdateQuery } from "mongoose";
import { IMetadata, Metadata } from "./mongoose_models/MetadataCardSchema";
import {
IMetadataRaw,
IStreakRaw,
Metadata,
} from "./mongoose_models/MetadataCardSchema";
import { closeMongooseConnection } from "./MongooseClient";

/**
* @description Reset the daily card review streaks.
*/
async function resetStreaks(): Promise<mongoDB.BulkWriteResult> {
const bulkWriteOps: {
updateOne: {
filter?: FilterQuery<IMetadata>;
update?: UpdateQuery<IMetadata>;
};
}[] = [];
const bulkWriteOps: mongoDB.AnyBulkWriteOperation<IMetadataRaw>[] = [];
const currentTimeStamp = Date.now();
const todaysDate = (new Date(currentTimeStamp)).toDateString();

const metadataDocs = await Metadata.find({ metadataIndex: 0 }).exec();
for (const metadataDoc of metadataDocs) {
const streakObj = {
timeStamp: metadataDoc.streak.get("timeStamp"),
cardIDs: metadataDoc.streak.get("cardIDs"),
length: metadataDoc.streak.get("length"),
dailyTarget: metadataDoc.streak.get("dailyTarget"),
const streakObj: IStreakRaw = {
cardIDs: metadataDoc.streak.get("cardIDs") || [],
length: metadataDoc.streak.get("length") || 0,
dailyTarget: metadataDoc.streak.get("dailyTarget") || 25,
timeStamp: metadataDoc.streak.get("timeStamp") || Date.now(),
};
const timeStampDate = (new Date(streakObj.timeStamp)).toDateString();
if (todaysDate !== timeStampDate) {
Expand All @@ -46,7 +44,14 @@ async function resetStreaks(): Promise<mongoDB.BulkWriteResult> {
bulkWriteOps.push({
updateOne: {
filter: { _id: metadataDoc._id },
update: { $set: { streak: streakObj } },
update: {
$set: {
"streak.cardIDs": streakObj.cardIDs,
"streak.length": streakObj.length,
"streak.timeStamp": streakObj.timeStamp,
"streak.dailyTarget": streakObj.dailyTarget,
},
},
},
});
}
Expand Down
6 changes: 4 additions & 2 deletions src/models/MetadataMongoDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

import * as fs from "fs/promises";

import { DeleteResult } from "mongodb";
import { FilterQuery } from "mongoose";
import { PUBLIC_USER_USERNAME } from "../config";
import { BaseResponse } from "../types";
import { Card, ICard } from "./mongoose_models/CardSchema";
Expand Down Expand Up @@ -94,7 +96,7 @@ type SavedCardParams = {
*/
export async function update(
savedCards: SavedCardParams[],
metadataQuery: Partial<IMetadata> | null = null,
metadataQuery: FilterQuery<IMetadata> | null = null,
attributeName: SortableCardAttribute = "urgency",
): Promise<IMetadata> {
/*
Expand Down Expand Up @@ -198,7 +200,7 @@ export async function updatePublicUserMetadata(
*/
export function deleteAllMetadata(
payload: Pick<IUser, "userIDInApp">,
): Promise<void> {
): Promise<DeleteResult> {
payload = sanitizeQuery(payload);
return Metadata.deleteMany({ createdById: payload.userIDInApp }).exec();
}
Expand Down
5 changes: 2 additions & 3 deletions src/models/MongooseClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,14 @@ import { connect, connection, disconnect } from "mongoose";
import { IS_DEV, MONGO_URI } from "../config";

// Already 5 by default, but I might need to increase it one day...
const connectionOptions = { poolSize: 12, useNewUrlParser: true };
let mongoServer: MongoMemoryServer | null = null;
if (IS_DEV) {
(async () => {
mongoServer = await MongoMemoryServer.create();
await connect(mongoServer.getUri(), connectionOptions);
await connect(mongoServer.getUri());
})();
} else {
connect(MONGO_URI, connectionOptions);
connect(MONGO_URI);
}

// Get the default connection (this will be registered on mongoose)
Expand Down
8 changes: 5 additions & 3 deletions src/models/mongoose_models/MetadataCardSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
*/
import { Document, model, Schema } from "mongoose";

export interface IStreak extends Map<string, any> {
export interface IStreakRaw {
cardIDs: Array<string>;
length: number;
dailyTarget: number;
timeStamp: number;
}

export type IStreak = IStreakRaw & Map<string, any>;

interface IMetadataNodeInformationEntry {
[id: string]: { urgency: number };
}
Expand Down Expand Up @@ -47,10 +49,10 @@ const metadataSchema = new Schema<IMetadataRaw>(
streak: {
type: Map,
default: {
cardIDs: [],
cardIDs: new Array<string>(),
length: 0,
dailyTarget: 25,
timeStamp: Date.now,
timeStamp: Date.now(),
},
},
cardsAreByDefaultPrivate: { type: Boolean, default: true },
Expand Down
2 changes: 1 addition & 1 deletion src/models/mongoose_models/Token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const tokenSchema = new Schema<ITokenRaw>(
token_id: {
type: String,
required: true,
unique: [true, "This token already exists"],
unique: true,
},
userIDInApp: { type: Number, immutable: true },
username: { type: String, immutable: true },
Expand Down
2 changes: 1 addition & 1 deletion src/models/mongoose_models/UserSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const userSchema = new Schema<IUserRaw>(
username: {
type: String,
required: true,
unique: [true, "This username is already taken"],
unique: true,
immutable: true,
match: /[_\-A-Za-z0-9]+/,
},
Expand Down
Loading