Skip to content

Commit

Permalink
Merge branch 'platform_part_2' into youtube-select-card
Browse files Browse the repository at this point in the history
  • Loading branch information
sspenst committed Dec 17, 2023
2 parents 91d21b3 + 2a9ac19 commit a505ef8
Show file tree
Hide file tree
Showing 16 changed files with 71 additions and 47 deletions.
5 changes: 4 additions & 1 deletion helpers/enrich.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,10 @@ export function getEnrichUserConfigPipelineStage(gameId: GameId, { localField, e
},
},
{
$unwind: '$config'
$unwind: {
path: '$config',
preserveNullAndEmptyArrays: true,
}
},

];
Expand Down
2 changes: 1 addition & 1 deletion helpers/getEmailBody.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* istanbul ignore file */
//* istanbul ignore file */

import GameLogoAndLabel from '@root/components/gameLogoAndLabel';
import { GameId } from '@root/constants/GameId';
Expand Down
5 changes: 1 addition & 4 deletions helpers/getRecordsByUserId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { GameId } from '@root/constants/GameId';
import Record from '@root/models/db/record';
import User from '@root/models/db/user';
import { PipelineStage, Types } from 'mongoose';
import dbConnect from '../lib/dbConnect';
import Level from '../models/db/level';
import Review from '../models/db/review';
import { LevelModel, RecordModel, ReviewModel } from '../models/mongoose';
Expand Down Expand Up @@ -120,10 +119,8 @@ export async function getRecordsByUserId(gameId: GameId, userId: Types.ObjectId,
}

export async function getReviewsForUserIdCount(gameId: GameId, id: string | string[] | undefined) {
await dbConnect();

try {
const levelsByUser = await LevelModel.find<Level>({ isDeleted: { $ne: true }, isDraft: false, userId: id, gameId: GameId }, '_id');
const levelsByUser = await LevelModel.find<Level>({ isDeleted: { $ne: true }, isDraft: false, userId: id, gameId: gameId }, '_id');
const reviews = await ReviewModel.find<Review>({
levelId: { $in: levelsByUser.map(level => level._id) },
}).countDocuments();
Expand Down
5 changes: 0 additions & 5 deletions helpers/getReviewsByUserId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,13 @@ import { GameId } from '@root/constants/GameId';
import cleanUser from '@root/lib/cleanUser';
import { LEVEL_SEARCH_DEFAULT_PROJECTION } from '@root/models/constants/projections';
import { PipelineStage, QueryOptions, Types } from 'mongoose';
import dbConnect from '../lib/dbConnect';
import Review from '../models/db/review';
import User from '../models/db/user';
import { LevelModel, ReviewModel } from '../models/mongoose';
import { getEnrichLevelsPipelineSteps } from './enrich';
import { logger } from './logger';

export async function getReviewsByUserId(gameId: GameId, id: string | string[] | undefined, reqUser: User | null = null, queryOptions: QueryOptions = {}) {
await dbConnect();

try {
const lookupPipelineUser: PipelineStage[] = getEnrichLevelsPipelineSteps(reqUser);

Expand Down Expand Up @@ -67,8 +64,6 @@ export async function getReviewsByUserId(gameId: GameId, id: string | string[] |
}

export async function getReviewsByUserIdCount(gameId: GameId, id: string | string[] | undefined) {
await dbConnect();

try {
const reviews = await ReviewModel.find<Review>({ userId: id, isDeleted: { $ne: true }, gameId: gameId }).countDocuments();

Expand Down
5 changes: 0 additions & 5 deletions helpers/getReviewsForUserId.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { GameId } from '@root/constants/GameId';
import { PipelineStage, QueryOptions, Types } from 'mongoose';
import cleanUser from '../lib/cleanUser';
import dbConnect from '../lib/dbConnect';
import Level from '../models/db/level';
import Review from '../models/db/review';
import User from '../models/db/user';
Expand All @@ -10,8 +9,6 @@ import { getEnrichLevelsPipelineSteps, getEnrichUserConfigPipelineStage } from '
import { logger } from './logger';

export async function getReviewsForUserId(gameId: GameId, id: string | string[] | undefined, reqUser: User | null = null, queryOptions: QueryOptions = {}) {
await dbConnect();

try {
const lookupPipelineUser: PipelineStage[] = getEnrichLevelsPipelineSteps(reqUser);

Expand Down Expand Up @@ -128,8 +125,6 @@ export async function getReviewsForUserId(gameId: GameId, id: string | string[]
}

export async function getReviewsForUserIdCount(gameId: GameId, id: string | string[] | undefined) {
await dbConnect();

try {
const levelsByUser = await LevelModel.find<Level>({ isDeleted: { $ne: true }, isDraft: false, userId: id, gameId: gameId }, '_id');
const reviews = await ReviewModel.find<Review>({
Expand Down
3 changes: 0 additions & 3 deletions helpers/getUsersWithMultiplayerProfile.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { GameId } from '@root/constants/GameId';
import dbConnect from '@root/lib/dbConnect';
import { FilterQuery, PipelineStage, Types } from 'mongoose';
import cleanUser from '../lib/cleanUser';
import { UserWithMultiplayerProfile } from '../models/db/user';
Expand All @@ -18,8 +17,6 @@ export async function getUsersWithMultiplayerProfile(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
project: { [field: string]: any },
): Promise<UserWithMultiplayerProfile[]> {
await dbConnect();

const users = await UserModel.aggregate([
{
$match: match
Expand Down
2 changes: 1 addition & 1 deletion helpers/isCurator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Role from '../constants/role';
import User, { ReqUser } from '../models/db/user';

export default function isCurator(user: User | ReqUser | undefined) {
export default function isCurator(user: User | ReqUser | null | undefined) {
return user?.roles?.includes(Role.ADMIN) || user?.roles?.includes(Role.CURATOR);
}
13 changes: 12 additions & 1 deletion lib/initializeLocalDb.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { EmailDigestSettingType } from '@root/constants/emailDigest';
import { getGameFromId } from '@root/helpers/getGameIdFromReq';
import UserConfig from '@root/models/db/userConfig';
import { AttemptContext } from '@root/models/schemas/playAttemptSchema';
import { PASSWORD_SALTROUNDS } from '@root/models/schemas/userSchema';
import { getNewUserConfig } from '@root/pages/api/user-config';
import bcrypt from 'bcryptjs';
import { Types } from 'mongoose';
import { DEFAULT_GAME_ID, GameId } from '../constants/GameId';
Expand All @@ -13,6 +14,16 @@ import Collection from '../models/db/collection';
import Level from '../models/db/level';
import { CampaignModel, CollectionModel, LevelModel, PlayAttemptModel, RecordModel, ReviewModel, StatModel, UserConfigModel, UserModel } from '../models/mongoose';

function getNewUserConfig(gameId: GameId, tutorialCompletedAt: number, userId: Types.ObjectId, params?: Partial<UserConfig>) {
return {
gameId: gameId,
theme: getGameFromId(gameId).defaultTheme,
tutorialCompletedAt: tutorialCompletedAt,
userId: userId,
...params,
} as Partial<UserConfig>;
}

export default async function initializeLocalDb() {
const ts = TimerUtil.getTs() - 60;

Expand Down
4 changes: 0 additions & 4 deletions models/schemas/userConfigSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@ import UserConfig from '../db/userConfig';

const UserConfigSchema = new mongoose.Schema<UserConfig>(
{
_id: {
type: mongoose.Schema.Types.ObjectId,
required: true,
},
calcRankedSolves: {
type: Number,
required: true,
Expand Down
2 changes: 1 addition & 1 deletion pages/[subdomain]/users/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
ts: 1,
}
},
...getEnrichUserConfigPipelineStage(gameId),
...getEnrichUserConfigPipelineStage(gameId), // TODO: Figure out wtf we need to do this twice?
{ $sort: sortObj.reduce((acc, cur) => ({ ...acc, [cur[0]]: cur[1] }), {}) },
{ '$facet': {
metadata: [ { $count: 'totalRows' } ],
Expand Down
12 changes: 10 additions & 2 deletions pages/api/signup/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import getTokenCookie from '../../../lib/getTokenCookie';
import sendPasswordResetEmail from '../../../lib/sendPasswordResetEmail';
import User from '../../../models/db/user';
import { UserConfigModel, UserModel } from '../../../models/mongoose';
import { getNewUserConfig } from '../user-config';

async function createUser({ gameId, email, name, password, tutorialCompletedAt, roles }: {gameId: GameId, email: string, name: string, password: string, tutorialCompletedAt: number, roles: Role[]}, queryOptions: QueryOptions): Promise<[User, UserConfig]> {
const id = new Types.ObjectId();
Expand All @@ -48,7 +47,16 @@ async function createUser({ gameId, email, name, password, tutorialCompletedAt,
score: 0,
ts: TimerUtil.getTs(),
}], queryOptions),
UserConfigModel.create([getNewUserConfig(gameId, tutorialCompletedAt, id)], queryOptions),
UserConfigModel.create([
{

gameId: gameId,
theme: getGameFromId(gameId).defaultTheme,
tutorialCompletedAt: tutorialCompletedAt,
userId: id,
}

], queryOptions),
]);

const user = userCreated[0] as User;
Expand Down
23 changes: 8 additions & 15 deletions pages/api/user-config/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { GameId } from '@root/constants/GameId';
import NotificationType from '@root/constants/notificationType';
import { getGameFromId } from '@root/helpers/getGameIdFromReq';
import isGuest from '@root/helpers/isGuest';
import { logger } from '@root/helpers/logger';
Expand All @@ -11,24 +10,18 @@ import { ValidArray, ValidNumber, ValidType } from '../../../helpers/apiWrapper'
import withAuth, { NextApiRequestWithAuth } from '../../../lib/withAuth';
import { UserConfigModel, UserModel } from '../../../models/mongoose';

// TODO: this function is kind of useless now. consider removing it
export function getNewUserConfig(gameId: GameId, tutorialCompletedAt: number, userId: Types.ObjectId, params?: Partial<UserConfig>) {
return {
_id: new Types.ObjectId(),

gameId: gameId,
theme: getGameFromId(gameId).defaultTheme,
tutorialCompletedAt: tutorialCompletedAt,
userId: userId,
...params,
} as Partial<UserConfig>;
}

export async function getUserConfig(gameId: GameId, user: User) {
let userConfig = await UserConfigModel.findOne({ userId: user._id, gameId: gameId }, { '__v': 0 }).lean<UserConfig>();

if (!userConfig) {
userConfig = await UserConfigModel.create(getNewUserConfig(gameId, 0, user._id));
userConfig = await UserConfigModel.create({

gameId: gameId,
theme: getGameFromId(gameId).defaultTheme,
tutorialCompletedAt: 0,
userId: user._id,

});
}

return userConfig;
Expand Down
6 changes: 4 additions & 2 deletions server/scripts/migrateFields.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import dbConnect, { dbDisconnect } from '@root/lib/dbConnect';
import { rawDbConnect, rawDbDisconnect } from './rawDbconnect';

/**
* Migrates specified fields from one collection to another.
Expand All @@ -9,7 +10,8 @@ import dbConnect, { dbDisconnect } from '@root/lib/dbConnect';
*/
export async function migrateFields(sourceModel: any, targetModel: any, fieldsToMigrate: any, localField: string, foreignField: string, matchQuery: any = {}) {
console.log('Starting the database connection...');
await dbConnect();
const conn = await rawDbConnect();

console.log('Database connected.');

console.log('Starting the aggregation pipeline...');
Expand Down Expand Up @@ -73,7 +75,7 @@ export async function migrateFields(sourceModel: any, targetModel: any, fieldsTo
console.log('Aggregation pipeline completed in ' + timeTakenSeconds + ' seconds.');

console.log('Closing the database connection...');
await dbDisconnect();
await rawDbDisconnect(conn);
console.log('Database disconnected.');

console.log('Migration completed successfully.');
Expand Down
27 changes: 27 additions & 0 deletions server/scripts/rawDbconnect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import mongoose, { ConnectOptions } from 'mongoose';

export async function rawDbConnect() {
const uri = process.env.MONGODB_URI;

if (!uri) {
throw new Error('MONGODB_URI not defined');
}

const options: ConnectOptions = {
connectTimeoutMS: 10000,
heartbeatFrequencyMS: 30000,
serverSelectionTimeoutMS: 10000,
socketTimeoutMS: 20000,
};
const val = await mongoose.connect(uri, options).then((mongoose) => {
return mongoose;
});

return val;
}

export async function rawDbDisconnect(connection: any) {
if (connection.conn) {
await connection.conn.disconnect();
}
}
2 changes: 1 addition & 1 deletion tests/pages/api/match/elo.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { calculateEloChange } from '../../../../pages/api/match';
import { calculateEloChange } from '@root/pages/api/match';

describe('elo testing', () => {
test('elo same rating testing regular', async () => {
Expand Down
2 changes: 1 addition & 1 deletion tests/pages/users/users.page.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe('pages/users page', () => {
expect(ret).toBeDefined();
expect(ret.props).toBeDefined();
expect(ret.props.searchQuery).toStrictEqual(DEFAULT_QUERY);
expect(ret.props.totalRows).toBe(5);
expect(ret.props.totalRows).toBe(6);
expect(ret.props.users[0].reviewCount).toBeUndefined();
}
);
Expand Down

0 comments on commit a505ef8

Please sign in to comment.