ENCOA-277, ENCOA-276, ENCOA-282, ENCOA-283
This commit is contained in:
74
src/pages/api/groups/controller.ts
Normal file
74
src/pages/api/groups/controller.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
|
||||
import { sessionOptions } from '@/lib/session';
|
||||
import { withIronSessionApiRoute } from 'iron-session/next';
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
import client from "@/lib/mongodb";
|
||||
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { op } = req.query
|
||||
|
||||
if (req.method === 'GET') {
|
||||
switch (op) {
|
||||
default:
|
||||
res.status(400).json({ error: 'Invalid operation!' })
|
||||
}
|
||||
}
|
||||
else if (req.method === 'POST') {
|
||||
switch (op) {
|
||||
case 'crossRefOwnership':
|
||||
res.status(200).json(await crossRefOwnership(req.body));
|
||||
break;
|
||||
case 'getIds':
|
||||
res.status(200).json(await getIds(req.body));
|
||||
break;
|
||||
default:
|
||||
res.status(400).json({ error: 'Invalid operation!' })
|
||||
}
|
||||
} else {
|
||||
res.status(400).end(`Method ${req.method} Not Allowed`)
|
||||
}
|
||||
}
|
||||
|
||||
async function crossRefOwnership(body: any): Promise<string[]> {
|
||||
const { userId, classrooms } = body;
|
||||
|
||||
// First find which classrooms from input exist
|
||||
const existingClassrooms = await db.collection('groups')
|
||||
.find({ name: { $in: classrooms } })
|
||||
.project({ name: 1, admin: 1, _id: 0 })
|
||||
.toArray();
|
||||
|
||||
// From those existing classrooms, return the ones where user is NOT the admin
|
||||
return existingClassrooms
|
||||
.filter(classroom => classroom.admin !== userId)
|
||||
.map(classroom => classroom.name);
|
||||
}
|
||||
|
||||
async function getIds(body: any): Promise<Record<string, string>> {
|
||||
const { names, userEmails } = body;
|
||||
|
||||
const existingGroups: any[] = await db.collection('groups')
|
||||
.find({ name: { $in: names } })
|
||||
.project({ name: 1, id: 1, _id: 0 })
|
||||
.toArray();
|
||||
|
||||
const users: any[] = await db.collection('users')
|
||||
.find({ email: { $in: userEmails } })
|
||||
.project({ email: 1, id: 1, _id: 0 })
|
||||
.toArray();
|
||||
|
||||
return {
|
||||
groups: existingGroups.reduce((acc, group) => {
|
||||
acc[group.name] = group.id;
|
||||
return acc;
|
||||
}, {} as Record<string, string>),
|
||||
users: users.reduce((acc, user) => {
|
||||
acc[user.email] = user.id;
|
||||
return acc;
|
||||
}, {} as Record<string, string>)
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user