Skip to content

Commit

Permalink
Merging issues plus some good design practice
Browse files Browse the repository at this point in the history
  • Loading branch information
TylerSchaefer4 committed Sep 25, 2023
1 parent 03f2dad commit c020ee4
Show file tree
Hide file tree
Showing 8 changed files with 138 additions and 169 deletions.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import IntakeTest from "@/models/intakeTest";
import prisma from "./client";

const persistentIntakeTestInstance = new IntakeTest(prisma.intakeTest)
const persistentIntakeTestInstance = new IntakeTest(prisma.intakeTest);

export default persistentIntakeTestInstance;
export default persistentIntakeTestInstance;
File renamed without changes.
72 changes: 26 additions & 46 deletions src/models/users.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PrismaClient,User } from "@prisma/client";
import { PrismaClient, User } from "@prisma/client";

import isEmail from "isemail";
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
Expand All @@ -15,70 +15,50 @@ interface UserData {

// Uer Information that is Insensitive
export interface InsensitiveUserInformation {
email?: string | null,
phoneNumber?: string | null,
firstName?: string | null,
lastName?: string | null,
email?: string | null;
phoneNumber?: string | null;
firstName?: string | null;
lastName?: string | null;
}
const UNIQUE_CONSTRAINT_ERROR_CODE = "P2002";

export default class Users {
constructor(private readonly usersDB: PrismaClient["user"]) {}



//updates the user of the given id with the given data given of type object and returns the userinformation
//updates the user of the given id with the given data given of type object and returns the userinformation
// which is shown nowhere or returns an err
public async updateUserById(id: number, updatedData: object) {
try {
const UserInformation: User | null = await this.usersDB.update({
where: {id:
id},
where: { id: id },
data: updatedData,
})
return UserInformation
}
catch (err) {
throw "Error: there is not proper data that was given"
});
return UserInformation;
} catch (err) {
throw "Error: there is not proper data that was given";
}
}

//gets the user id number to find if there is a singular user with the id number and returns the info it has
public async getUserById(id: number) {
try {
const UserInformation: User | null = await this.usersDB.findUnique({
where: {
id : id
},
})
return UserInformation
}
catch (err) {
throw "User is not an integer"
}
}

// Get Insensitive User Information By ID
public async getUserById(id: number) {

try {
// Select Insensitive User Information from Database based on ID
const UserInformation: InsensitiveUserInformation | null = await this.usersDB.findUnique({
where: {
id
},
select: {
id: true,
email: true,
phoneNumber: true,
firstName: true,
lastName: true,
}
});

const UserInformation: InsensitiveUserInformation | null =
await this.usersDB.findUnique({
where: {
id,
},
select: {
id: true,
email: true,
phoneNumber: true,
firstName: true,
lastName: true,
},
});

return UserInformation;
}
catch (Error) {
} catch (Error) {
throw "Error: User ID is not an Number";
}
}
Expand Down
204 changes: 97 additions & 107 deletions src/pages/api/users/[id].ts
Original file line number Diff line number Diff line change
@@ -1,163 +1,153 @@
// GET, PUT, DELETE operations for a specific user by ID
import type { NextApiRequest, NextApiResponse } from "next";
import persistentUserInstance from "../../../../prisma/persistentUserInstance";
import persistentUserInstance from "../../../../lib/persistentUserInstance";
import { getServerSession } from "next-auth";
import { authOptions } from "../auth/[...nextauth]";
import Users from "@/models/users";
import { error } from "console";
import { PrismaClient, User } from '@prisma/client';
import { PrismaClient, User } from "@prisma/client";
const prisma = new PrismaClient();

import { InsensitiveUserInformation } from "@/models/users";


type Message = {
message?: string;
};

message?: string;
};

export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Message>
) {
const session = await getServerSession(req, res, authOptions);
console.log("hello")
console.log("hello");
const supportedRequestMethods: { [key: string]: Function } = {
GET: getUser,
// these two below are currently seperated with differnet functions in case there is any
// these two below are currently seperated with differnet functions in case there is any
// edits needed to be made to a patch or put to ensure
// a more secure and validated request other than the built in prisma checks
PUT: updateUser,
PATCH: updateUserPatch,
};
console.log(req.body)
console.log(req.body);

if (req.method) {
return supportedRequestMethods[req.method](req, res, session);
}
return res.status(405).send({ message: "request method not supported" });
}

//this is the get function which simply takes in the id given fro mthe request query and then checks to see if that number
// is a valid id to then is confirming that the user exists
async function getUser(
req: NextApiRequest,
res: NextApiResponse
) {

let id: number;

try {
id = Number(req.query.id)
if(typeof id !== 'number') {
throw Error ("plesae input number")
}
} catch (error) {
return res.status(403).send({ message: String(error) });

}
try {
const userInfo = await persistentUserInstance.getUserById(id);
return res.status(200).send({ message: userInfo })
} catch(error) {
return res.status(403).send({ message: String(error) });
}

}



//updating user with a PULL request this will check if the user exits attempts to get the user
//updating user with a PULL request this will check if the user exits attempts to get the user
// as a double confimration that there is data for this user then it will pass to a method in ../models/users.ts
// then comes back adn prints if it was succesful update or not
async function updateUser(
req: NextApiRequest,
res: NextApiResponse
) {

let id: number;
async function updateUser(req: NextApiRequest, res: NextApiResponse) {
let id: number;

try {
id = Number(req.query.id)
if(typeof id !== 'number') {
throw Error ("plesae input number")
} } catch (error) {
try {
id = Number(req.query.id);
if (typeof id !== "number") {
throw Error("plesae input number");
}
} catch (error) {
return res.status(403).send({ message: String(error) });
}

const reqProp = [
"firstName",
"lastName",
"dob",
"phoneNumber",
"email",
"emailVerified",
"gender",
"age",
"ethnicity",
"education",
"maritalStatus",
"password",
"verified",
"isAdmin",
"languages",
"employmentStatus",
"householdIncome",
"livingStatus",
];
const missProp = [];

// this chunk ensures that the needed items for a put requests are there and if not lets the user know what is missing
for (const prop of reqProp) {
if (req.body[prop] === undefined) {
missProp.push(prop);
}
}
if (missProp.length > 0) {
return res
.status(400)
.json({ error: `Missing required properties: ${missProp.join(", ")}` });
}

const reqProp = ['firstName', 'lastName', 'dob', 'phoneNumber', 'email', 'emailVerified',
'gender', 'age', 'ethnicity', 'education', 'maritalStatus', 'password', 'verified',
'isAdmin', 'languages', 'employmentStatus', 'householdIncome', 'livingStatus'];
const missProp = []

// this chunk ensures that the needed items for a put requests are there and if not lets the user know what is missing
for (const prop of reqProp) {
if (req.body[prop] === undefined) {
missProp.push(prop);
}
}
if (missProp.length > 0) {
return res.status(400).json({ error: `Missing required properties: ${missProp.join(', ')}` });
}

try {
try {
const user = await persistentUserInstance.getUserById(id);
} catch (err) {
return res.status(404).send({ message: "User not found" });
}

try {
const updateUser = await persistentUserInstance.updateUserById(id,req.body);
return res.status(200).send({ message: "updated user"})
} catch(error) {
return res.status(403).send({ message: "user was not properly updated" });
}
} catch (err) {
return res.status(404).send({ message: "User not found" });
}

try {
const updateUser = await persistentUserInstance.updateUserById(
id,
req.body
);
return res.status(200).send({ message: "updated user" });
} catch (error) {
return res.status(403).send({ message: "user was not properly updated" });
}
}

//updating user with a PATCH request this will check if the user exits attempts to get the user
//updating user with a PATCH request this will check if the user exits attempts to get the user
// as a double confimration that there is data for this user then it will pass to a method in ../models/users.ts
// which is give the query body then comes back and prints if it was succesful update or not
async function updateUserPatch(
req: NextApiRequest,
res: NextApiResponse
) {
let id: number;

try {
id = Number(req.query.id)
if(typeof id !== 'number') {
throw Error ("plesae input number")
} } catch (error) {
throw res.status(403).send({ message: String(error) });
async function updateUserPatch(req: NextApiRequest, res: NextApiResponse) {
let id: number;

try {
id = Number(req.query.id);
if (typeof id !== "number") {
throw Error("plesae input number");
}
try {
} catch (error) {
throw res.status(403).send({ message: String(error) });
}
try {
const user = await persistentUserInstance.getUserById(id);
} catch (err) {
throw res.status(404).send({ message: "User not found" });
}
} catch (err) {
throw res.status(404).send({ message: "User not found" });
}

try {
const updateUser = await persistentUserInstance.updateUserById(id, req.body);
throw res.status(200).send({ message: "updated user thank you" })
} catch(error) {
throw res.status(403).send({ message: "user was not properly updated in patch" });
try {
const updateUser = await persistentUserInstance.updateUserById(
id,
req.body
);
throw res.status(200).send({ message: "updated user thank you" });
} catch (error) {
throw res
.status(403)
.send({ message: "user was not properly updated in patch" });
}
}

async function getUser(
req: NextApiRequest,
res: NextApiResponse<Message | InsensitiveUserInformation>
) {
let id = Number(req.query.id);
let id = Number(req.query.id);

try {
const userInfo = await persistentUserInstance.getUserById(id);
if (!userInfo || Object.keys(userInfo).length === 0) {
return res.status(404).send({message: "User not found"})
}
return res.status(200).send(userInfo);
} catch (error) {
return res.status(403).send({ message: String(error) });
try {
const userInfo = await persistentUserInstance.getUserById(id);
if (!userInfo || Object.keys(userInfo).length === 0) {
return res.status(404).send({ message: "User not found" });
}
return res.status(200).send(userInfo);
} catch (error) {
return res.status(403).send({ message: String(error) });
}
}
2 changes: 1 addition & 1 deletion src/pages/api/users/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { NextApiRequest, NextApiResponse } from "next";
import persistentUserInstance from "../../../../prisma/persistentUserInstance";
import persistentUserInstance from "../../../../lib/persistentUserInstance";
import { getServerSession } from "next-auth";
import { authOptions } from "../auth/[...nextauth]";

Expand Down
Loading

0 comments on commit c020ee4

Please sign in to comment.