import { ObjectId } from 'bson'; import express from 'express'; import passport from 'passport'; import { MongoShelf } from '../models/shelf'; import { DB_NAME, getDatabaseClient } from '../db-utils'; import { MongoCategory } from '../models/category'; import { MongoUser } from '../models/user'; import { Word } from '../models/word'; export const userProfileRoutes = express.Router(); export const jwtAuthentication = passport.authenticate('jwt', { session: false }); userProfileRoutes.get('/profile/', jwtAuthentication, async (request, response) => { const user: MongoUser = (request.user as any); response.json({ _id: user._id, name: user.name, email: user.email, isVerified: user.isVerified, categories: user.categories, uncategorised: user.uncategorised }); return; }); userProfileRoutes.get('/profile/deep-copy/', jwtAuthentication, async (request, response) => { const user: MongoUser = (request.user as any); const categoryCollection = getDatabaseClient().db(DB_NAME).collection('categories'); const shelfCollection = getDatabaseClient().db(DB_NAME).collection('shelves'); const wordCollection = getDatabaseClient().db(DB_NAME).collection('words'); let deepCategories = []; for (let i = 0; i < user.categories.length; i += 1) { let deepShelves = []; const matchedCategory: any = await categoryCollection.findOne({ _id: new ObjectId(user.categories[i]) }); if (matchedCategory && matchedCategory.shelves) { for (let j = 0; j < matchedCategory.shelves.length; j += 1) { let deepAddedWords = []; const matchedShelf: any = await shelfCollection.findOne({ _id: new ObjectId(matchedCategory.shelves[j]) }); if (matchedShelf && matchedShelf.addedWords) { for (let k = 0; k < matchedShelf.addedWords.length; k += 1) { const matchedWord = await wordCollection.findOne({ _id: new ObjectId(matchedShelf.addedWords[k].word) }); if (matchedWord) { deepAddedWords.push(matchedWord); } } } matchedShelf.addedWords = deepAddedWords; deepShelves.push(matchedShelf); } } matchedCategory.shelves = deepShelves; deepCategories.push(matchedCategory); } let deepUncategorisedAddedWords = []; const matchedUncategoisedShelf: any = await shelfCollection.findOne({ _id: new ObjectId(user.uncategorised) }); if (matchedUncategoisedShelf && matchedUncategoisedShelf.addedWords) { for (let k = 0; k < matchedUncategoisedShelf.addedWords.length; k += 1) { const matchedWord = await wordCollection.findOne({ _id: new ObjectId(matchedUncategoisedShelf.addedWords[k].word) }); if (matchedWord) { deepUncategorisedAddedWords.push(matchedWord); } } matchedUncategoisedShelf.addedWords = deepUncategorisedAddedWords; } response.json({ _id: user._id, name: user.name, email: user.email, isVerified: user.isVerified, categories: deepCategories, uncategorised: matchedUncategoisedShelf }); return; });