Skip to content

Commit

Permalink
[Deps] Update to Mongoose 7 (#172)
Browse files Browse the repository at this point in the history
  • Loading branch information
dchege711 authored Jun 15, 2024
1 parent 6e91d22 commit ef5a1c1
Show file tree
Hide file tree
Showing 12 changed files with 142 additions and 104 deletions.
72 changes: 60 additions & 12 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
"markdown-it": "^14.1.0",
"markdown-it-texmath": "^1.0.0",
"mongodb": "^4.17.2",
"mongoose": "^6.13.0",
"mongoose": "^7.6.13",
"nodemailer": "^6.9.9",
"path": "0.12.7",
"sjcl": "1.0.7",
Expand Down
38 changes: 22 additions & 16 deletions src/models/CardsMongoDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@
*/

import { FilterQuery, SortOrder } from "mongoose";
import { BaseResponse } from "../types";
import * as MetadataDB from "./MetadataMongoDB";
import { Card, ICard, ICardRaw } from "./mongoose_models/CardSchema";
import { Card, ICard, ICardDocument } from "./mongoose_models/CardSchema";
import { sanitizeCard, sanitizeQuery } from "./SanitizationAndValidation";

export type CreateCardParams = Pick<
Expand Down Expand Up @@ -48,15 +47,20 @@ export async function create(unsavedCard: CreateCardParams): Promise<ICard> {
*/
export async function createMany(
unsavedCards: CreateCardParams[],
): Promise<ICard[]> {
): Promise<Partial<ICard>[]> {
const sanitizedCards = unsavedCards.map((card) => sanitizeCard(card));
const cards = await Card.insertMany(sanitizedCards);
return Promise.all([
MetadataDB.update(cards.map((card) => ({ card, previousTags: "" }))),
MetadataDB.updatePublicUserMetadata(
cards.map((card) => ({ card, previousTags: "" })),
),
]).then(() => cards);
await MetadataDB.update(
cards.map((
card,
) => ({ card, previousTags: "" } as MetadataDB.SavedCardParams)),
);
await MetadataDB.updatePublicUserMetadata(
cards.map((
card,
) => ({ card, previousTags: "" } as MetadataDB.SavedCardParams)),
);
return cards;
}

export interface ReadCardParams {
Expand All @@ -79,7 +83,7 @@ export function read(
payload: ReadCardParams,
projection =
"title description descriptionHTML tags urgency createdById isPublic",
): Promise<ICardRaw | null> {
): Promise<ICard | null> {
payload = sanitizeQuery(payload);
const query: FilterQuery<ICard> = { createdById: payload.userIDInApp };
if (payload.cardID) { query._id = payload.cardID; }
Expand All @@ -92,7 +96,7 @@ export function read(
*
* @returns {Promise} resolves with the updated card.
*/
export async function update(payload: Partial<ICard>): Promise<ICardRaw> {
export async function update(payload: Partial<ICard>): Promise<ICard> {
payload = sanitizeCard(payload);
const oldCard = await Card.findByIdAndUpdate(
payload._id,
Expand Down Expand Up @@ -126,7 +130,7 @@ export interface SearchCardParams {
limit: number;
creationStartDate?: Date;
creationEndDate?: Date;
// TODO: Change this to Array<Pick<ICardRaw, "_id">>?
// TODO: Change this to Array<Pick<ICard, "_id">>?
cardIDs?: string;
}

Expand All @@ -147,7 +151,7 @@ interface CardQuery {
}

const kCardsSearchProjection = "title tags urgency";
type CardsSearchResult = Pick<ICardRaw, "_id" | "title" | "tags" | "urgency">;
type CardsSearchResult = Pick<ICard, "_id" | "title" | "tags" | "urgency">;

/**
* @description Search for cards with associated key words. Search should be
Expand Down Expand Up @@ -303,7 +307,7 @@ export type ReadPublicCardParams = Omit<ReadCardParams, "userIDInApp">;
*/
export function readPublicCard(
payload: ReadPublicCardParams,
): Promise<ICardRaw | null> {
): Promise<ICard | null> {
return _readPublicCard(payload);
}

Expand All @@ -316,7 +320,9 @@ export function readPublicCard(
*
* [1]: https://github.com/trpc/trpc/discussions/3661
*/
function _readPublicCard(payload: ReadPublicCardParams): Promise<ICard | null> {
function _readPublicCard(
payload: ReadPublicCardParams,
): Promise<ICardDocument | null> {
payload = sanitizeQuery(payload);
if (payload.cardID === undefined) {
return Promise.reject("cardID is undefined");
Expand Down Expand Up @@ -388,7 +394,7 @@ export interface FlagCardParams {
* @returns {Promise} takes a JSON object with `success`, `status` and `message`
* as its keys. If successful, the message will contain the saved card.
*/
export async function flagCard(payload: FlagCardParams): Promise<ICardRaw> {
export async function flagCard(payload: FlagCardParams): Promise<ICard> {
payload = sanitizeQuery(payload);
const flagsToUpdate: Partial<
Pick<ICard, "numTimesMarkedAsDuplicate" | "numTimesMarkedForReview">
Expand Down
42 changes: 16 additions & 26 deletions src/models/DailyTasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,23 @@

import * as mongoDB from "mongodb";

import {
IMetadataRaw,
IStreakRaw,
Metadata,
} from "./mongoose_models/MetadataCardSchema";
import { IStreak, Metadata } from "./mongoose_models/MetadataCardSchema";
import { closeMongooseConnection } from "./MongooseClient";

/**
* @description Reset the daily card review streaks.
*/
async function resetStreaks(): Promise<mongoDB.BulkWriteResult> {
const bulkWriteOps: mongoDB.AnyBulkWriteOperation<IMetadataRaw>[] = [];
async function resetStreaks(): Promise<void> {
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: 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 streakObj: IStreak = {
cardIDs: metadataDoc.streak.cardIDs || [],
length: metadataDoc.streak.length || 0,
dailyTarget: metadataDoc.streak.dailyTarget || 25,
timeStamp: metadataDoc.streak.timeStamp || Date.now(),
};
const timeStampDate = (new Date(streakObj.timeStamp)).toDateString();
if (todaysDate !== timeStampDate) {
Expand All @@ -41,28 +36,23 @@ async function resetStreaks(): Promise<mongoDB.BulkWriteResult> {
}
streakObj.cardIDs = [];
streakObj.timeStamp = currentTimeStamp;
bulkWriteOps.push({
updateOne: {
filter: { _id: metadataDoc._id },
update: {
$set: {
"streak.cardIDs": streakObj.cardIDs,
"streak.length": streakObj.length,
"streak.timeStamp": streakObj.timeStamp,
"streak.dailyTarget": streakObj.dailyTarget,
},
},

await Metadata.findByIdAndUpdate(metadataDoc._id, {
$set: {
"streak.cardIDs": streakObj.cardIDs,
"streak.length": streakObj.length,
"streak.timeStamp": streakObj.timeStamp,
"streak.dailyTarget": streakObj.dailyTarget,
},
});
}
return Metadata.bulkWrite(bulkWriteOps);
}

if (require.main === module) {
resetStreaks()
.then((result) => {
.then(() => {
console.log(
`Reset the streak counters for ${result.modifiedCount} documents`,
`Reset the streak counters for documents`,
);
return closeMongooseConnection();
})
Expand Down
Loading

0 comments on commit ef5a1c1

Please sign in to comment.