Skip to content

Commit

Permalink
add mailingLists to endpoints and UsersOnMailingLists model
Browse files Browse the repository at this point in the history
  • Loading branch information
135ze committed Nov 30, 2024
1 parent 5f22cd1 commit 76ac98c
Show file tree
Hide file tree
Showing 9 changed files with 172 additions and 25 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- CreateTable
CREATE TABLE "UsersOnMailingLists" (
"userId" INTEGER NOT NULL,
"mailingListId" INTEGER NOT NULL,

CONSTRAINT "UsersOnMailingLists_pkey" PRIMARY KEY ("userId","mailingListId")
);

-- AddForeignKey
ALTER TABLE "UsersOnMailingLists" ADD CONSTRAINT "UsersOnMailingLists_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "UsersOnMailingLists" ADD CONSTRAINT "UsersOnMailingLists_mailingListId_fkey" FOREIGN KEY ("mailingListId") REFERENCES "MailingList"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
29 changes: 20 additions & 9 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,17 @@ model Absence {
}

model User {
id Int @id @default(autoincrement())
authId String @unique
email String @unique
id Int @id @default(autoincrement())
authId String @unique
email String @unique
firstName String
lastName String
role Role @default(TEACHER)
status Status @default(INVITED)
numOfAbsences Int @default(10)
absences Absence[] @relation("absentTeacher")
substitutes Absence[] @relation("substituteTeacher")
role Role @default(TEACHER)
status Status @default(INVITED)
numOfAbsences Int @default(10)
absences Absence[] @relation("absentTeacher")
substitutes Absence[] @relation("substituteTeacher")
mailingLists UsersOnMailingLists[]
}

model Location {
Expand All @@ -44,9 +45,19 @@ model Location {
}

model MailingList {
id Int @id @default(autoincrement())
id Int @id @default(autoincrement())
name String
emails String[]
users UsersOnMailingLists[]
}

model UsersOnMailingLists {
user User @relation(fields: [userId], references: [id])
userId Int
mailingList MailingList @relation(fields: [mailingListId], references: [id])
mailingListId Int
@@id([userId, mailingListId])
}

model Subject {
Expand Down
98 changes: 98 additions & 0 deletions prisma/seed/.snaplet/dataModel.json
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,20 @@
"hasDefaultValue": false,
"isId": false,
"maxLength": null
},
{
"name": "UsersOnMailingLists",
"type": "UsersOnMailingLists",
"isRequired": false,
"kind": "object",
"relationName": "UsersOnMailingListsToMailingList",
"relationFromFields": [],
"relationToFields": [],
"isList": true,
"isId": false,
"isGenerated": false,
"sequence": false,
"hasDefaultValue": false
}
],
"uniqueConstraints": [
Expand Down Expand Up @@ -658,6 +672,20 @@
"isGenerated": false,
"sequence": false,
"hasDefaultValue": false
},
{
"name": "UsersOnMailingLists",
"type": "UsersOnMailingLists",
"isRequired": false,
"kind": "object",
"relationName": "UsersOnMailingListsToUser",
"relationFromFields": [],
"relationToFields": [],
"isList": true,
"isId": false,
"isGenerated": false,
"sequence": false,
"hasDefaultValue": false
}
],
"uniqueConstraints": [
Expand All @@ -678,6 +706,76 @@
}
]
},
"UsersOnMailingLists": {
"id": "public.UsersOnMailingLists",
"schemaName": "public",
"tableName": "UsersOnMailingLists",
"fields": [
{
"id": "public.UsersOnMailingLists.userId",
"name": "userId",
"columnName": "userId",
"type": "int4",
"isRequired": true,
"kind": "scalar",
"isList": false,
"isGenerated": false,
"sequence": false,
"hasDefaultValue": false,
"isId": true,
"maxLength": null
},
{
"id": "public.UsersOnMailingLists.mailingListId",
"name": "mailingListId",
"columnName": "mailingListId",
"type": "int4",
"isRequired": true,
"kind": "scalar",
"isList": false,
"isGenerated": false,
"sequence": false,
"hasDefaultValue": false,
"isId": true,
"maxLength": null
},
{
"name": "MailingList",
"type": "MailingList",
"isRequired": true,
"kind": "object",
"relationName": "UsersOnMailingListsToMailingList",
"relationFromFields": ["mailingListId"],
"relationToFields": ["id"],
"isList": false,
"isId": false,
"isGenerated": false,
"sequence": false,
"hasDefaultValue": false
},
{
"name": "User",
"type": "User",
"isRequired": true,
"kind": "object",
"relationName": "UsersOnMailingListsToUser",
"relationFromFields": ["userId"],
"relationToFields": ["id"],
"isList": false,
"isId": false,
"isGenerated": false,
"sequence": false,
"hasDefaultValue": false
}
],
"uniqueConstraints": [
{
"name": "UsersOnMailingLists_pkey",
"fields": ["mailingListId", "userId"],
"nullNotDistinct": false
}
]
},
"_prisma_migrations": {
"id": "public._prisma_migrations",
"schemaName": "public",
Expand Down
24 changes: 22 additions & 2 deletions prisma/seed/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,16 @@ const main = async () => {
StatusEnum.DEACTIVATED,
];

const numUsers = 5;
const numMailingLists = 10;
const userIds = Array.from({ length: numUsers }, (_, i) => i + 1);
const mailingListIds = Array.from(
{ length: numMailingLists },
(_, i) => i + 1
);

await seed.user((createMany) =>
createMany(5, () => ({
createMany(numUsers, () => ({
authId: faker.string.uuid(),
email: faker.internet.email(),
firstName: faker.person.firstName(),
Expand Down Expand Up @@ -151,7 +159,7 @@ const main = async () => {
);

await seed.mailingList((createMany) =>
createMany(10, () => {
createMany(numMailingLists, () => {
const subject = faker.helpers.arrayElement(subjects);
return {
name: subject.name,
Expand All @@ -160,6 +168,18 @@ const main = async () => {
})
);

for (const mailingListId of mailingListIds) {
const randomUserIds = faker.helpers.arrayElements(userIds, 3);
for (const userId of randomUserIds) {
await seed.usersOnMailingLists((createMany) =>
createMany(1, () => ({
mailingListId: mailingListId,
userId: userId,
}))
);
}
}

console.log('Database seeded successfully!');

process.exit();
Expand Down
10 changes: 9 additions & 1 deletion src/pages/api/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,16 @@ export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const params = req.query;
const getMailingLists = params.getMailingLists === 'true';

try {
const users = await prisma.user.findMany();
const users = await prisma.user.findMany({
include: {
mailingLists: getMailingLists,
},
});

res.status(200).json(users);
} catch (error) {
console.error('Error fetching users:', error);
Expand Down
15 changes: 6 additions & 9 deletions src/pages/api/users/[id].ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@ export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const id = Number(req.query.id);
const method = req.method;
const params = req.query;
const id = Number(params.id);

if (Number.isNaN(id)) {
return res.status(400).json({ error: 'Invalid ID provided' });
}

if (req.method === 'GET') {
const getAbsences = req.query.getAbsences === 'true';
if (method === 'GET') {
const getAbsences = params.getAbsences === 'true';

try {
const user = await prisma.user.findUnique({
Expand All @@ -29,13 +31,8 @@ export default async function handler(
console.error('Error fetching user:', error);
return res.status(500).json({ error: 'Internal server error' });
}
} else if (req.method === 'PATCH') {
} else if (method === 'PATCH') {
const { email, firstName, lastName, role, status } = req.body;
const id = Number(req.query.id as string);

if (Number.isNaN(id)) {
return res.status(400).json({ error: 'Invalid ID provided' });
}

try {
const updatedUser = await prisma.user.update({
Expand Down
4 changes: 2 additions & 2 deletions src/pages/api/users/email/[email].ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default async function handler(
res: NextApiResponse
) {
const params = req.query;
const shouldIncludeAbsences = params.shouldIncludeAbsences === 'true';
const getAbsences = params.getAbsences === 'true';
const realEmail = params.email as string;
try {
const useFake = true;
Expand All @@ -31,7 +31,7 @@ export default async function handler(

const user = await prisma.user.findUniqueOrThrow({
where: { email },
include: { absences: shouldIncludeAbsences },
include: { absences: getAbsences },
});

return res.status(200).json(user);
Expand Down
2 changes: 1 addition & 1 deletion src/pages/manage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ interface User {
numOfAbsences: string;
}

export default function AnotherPage() {
export default function Manage() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState<boolean>(true);

Expand Down
2 changes: 1 addition & 1 deletion src/pages/profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default function Profile() {
if (!session || !session.user || !session.user.email) return;

const email = session.user.email;
const apiUrl = `/api/users/email/${email}?shouldIncludeAbsences=true`;
const apiUrl = `/api/users/email/${email}?getAbsences=true`;

try {
const response = await fetch(apiUrl);
Expand Down

0 comments on commit 76ac98c

Please sign in to comment.