-
Notifications
You must be signed in to change notification settings - Fork 0
Implement UserLab schemas and apis #11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
AlexMeng0831
wants to merge
5
commits into
main
Choose a base branch
from
UserLab-schema-api
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| import { DELETE, GET, POST, PUT } from "@/app/api/UserLab/route"; | ||
| import { | ||
| addUserLab, | ||
| deleteUserLab, | ||
| getUserLab, | ||
| getUserLabs, | ||
| updateUserLab, | ||
| } from "@/services/UserLab"; | ||
|
|
||
| jest.mock("@/services/UserLab", () => ({ | ||
| getUserLabs: jest.fn(), | ||
| getUserLab: jest.fn(), | ||
| addUserLab: jest.fn(), | ||
| updateUserLab: jest.fn(), | ||
| deleteUserLab: jest.fn(), | ||
| })); | ||
|
|
||
| const mockedGetUserLabs = jest.mocked(getUserLabs); | ||
| const mockedGetUserLab = jest.mocked(getUserLab); | ||
| const mockedAddUserLab = jest.mocked(addUserLab); | ||
| const mockedUpdateUserLab = jest.mocked(updateUserLab); | ||
| const mockedDeleteUserLab = jest.mocked(deleteUserLab); | ||
|
|
||
| describe("UserLab API route", () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| it("returns a paginated list of user labs", async () => { | ||
| mockedGetUserLabs.mockResolvedValue({ | ||
| items: [{ _id: "1" }], | ||
| page: 2, | ||
| limit: 10, | ||
| total: 11, | ||
| totalPages: 2, | ||
| } as never); | ||
|
|
||
| const response = await GET( | ||
| new Request("http://localhost/api/UserLab?page=2&limit=10") | ||
| ); | ||
|
|
||
| expect(response.status).toBe(200); | ||
| await expect(response.json()).resolves.toEqual({ | ||
| items: [{ _id: "1" }], | ||
| page: 2, | ||
| limit: 10, | ||
| total: 11, | ||
| totalPages: 2, | ||
| }); | ||
| expect(mockedGetUserLabs).toHaveBeenCalledWith({ page: 2, limit: 10 }); | ||
| }); | ||
|
|
||
| it("returns 400 when pagination exceeds the allowed limit", async () => { | ||
| const response = await GET( | ||
| new Request("http://localhost/api/UserLab?limit=20") | ||
| ); | ||
|
|
||
| expect(response.status).toBe(400); | ||
| await expect(response.json()).resolves.toEqual({ | ||
| message: "Too big: expected number to be <=10", | ||
| }); | ||
| }); | ||
|
|
||
| it("returns 404 when a requested entry does not exist", async () => { | ||
| mockedGetUserLab.mockResolvedValue(null as never); | ||
|
|
||
| const response = await GET( | ||
| new Request("http://localhost/api/UserLab?id=507f1f77bcf86cd799439011") | ||
| ); | ||
|
|
||
| expect(response.status).toBe(404); | ||
| await expect(response.json()).resolves.toEqual({ | ||
| message: "UserLab not found", | ||
| }); | ||
| }); | ||
|
|
||
| it("defaults a new entry role to VIEWER", async () => { | ||
| mockedAddUserLab.mockResolvedValue({ _id: "1", role: "VIEWER" } as never); | ||
|
|
||
| const response = await POST( | ||
| new Request("http://localhost/api/UserLab", { | ||
| method: "POST", | ||
| body: JSON.stringify({ | ||
| user: "507f1f77bcf86cd799439011", | ||
| lab: "507f1f77bcf86cd799439012", | ||
| }), | ||
| }) | ||
| ); | ||
|
|
||
| expect(response.status).toBe(201); | ||
| expect(mockedAddUserLab).toHaveBeenCalledWith({ | ||
| user: "507f1f77bcf86cd799439011", | ||
| lab: "507f1f77bcf86cd799439012", | ||
| role: "VIEWER", | ||
| }); | ||
| }); | ||
|
|
||
| it("returns 500 when POST hits an unexpected error", async () => { | ||
| mockedAddUserLab.mockRejectedValue(new Error("db down")); | ||
|
|
||
| const response = await POST( | ||
| new Request("http://localhost/api/UserLab", { | ||
| method: "POST", | ||
| body: JSON.stringify({ | ||
| user: "507f1f77bcf86cd799439011", | ||
| lab: "507f1f77bcf86cd799439012", | ||
| role: "PI", | ||
| }), | ||
| }) | ||
| ); | ||
|
|
||
| expect(response.status).toBe(500); | ||
| await expect(response.json()).resolves.toEqual({ | ||
| message: "Internal server error", | ||
| }); | ||
| }); | ||
|
|
||
| it("returns 404 when PUT targets a missing entry", async () => { | ||
| mockedUpdateUserLab.mockResolvedValue(null as never); | ||
|
|
||
| const response = await PUT( | ||
| new Request("http://localhost/api/UserLab", { | ||
| method: "PUT", | ||
| body: JSON.stringify({ | ||
| id: "507f1f77bcf86cd799439011", | ||
| update: { role: "LAB_MANAGER" }, | ||
| }), | ||
| }) | ||
| ); | ||
|
|
||
| expect(response.status).toBe(404); | ||
| await expect(response.json()).resolves.toEqual({ | ||
| message: "UserLab not found", | ||
| }); | ||
| }); | ||
|
|
||
| it("returns 200 after deleting an entry", async () => { | ||
| mockedDeleteUserLab.mockResolvedValue({ _id: "1" } as never); | ||
|
|
||
| const response = await DELETE( | ||
| new Request("http://localhost/api/UserLab", { | ||
| method: "DELETE", | ||
| body: JSON.stringify({ | ||
| id: "507f1f77bcf86cd799439011", | ||
| }), | ||
| }) | ||
| ); | ||
|
|
||
| expect(response.status).toBe(200); | ||
| await expect(response.json()).resolves.toEqual({ | ||
| message: "UserLab deleted", | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| import { NextResponse } from "next/server"; | ||
| import { z } from "zod"; | ||
|
|
||
| import { userLabRoleValues } from "@/models/UserLab"; | ||
| import { | ||
| addUserLab, | ||
| deleteUserLab, | ||
| getUserLab, | ||
| getUserLabs, | ||
| updateUserLab, | ||
| } from "@/services/UserLab"; | ||
|
|
||
| const objectIdSchema = z | ||
| .string() | ||
| .regex(/^[0-9a-fA-F]{24}$/, "Invalid MongoDB ObjectId"); | ||
|
|
||
| const paginationSchema = z.object({ | ||
| page: z.coerce.number().int().positive().default(1), | ||
| limit: z.coerce.number().int().positive().max(10).default(10), | ||
| }); | ||
|
|
||
| const userLabBaseSchema = z.object({ | ||
| user: objectIdSchema, | ||
| lab: objectIdSchema, | ||
| role: z.enum(userLabRoleValues).optional(), | ||
| }); | ||
|
|
||
| const userLabUpdateSchema = userLabBaseSchema.partial(); | ||
|
|
||
| function handleRouteError(error: unknown) { | ||
| if (error instanceof z.ZodError) { | ||
| return NextResponse.json( | ||
| { message: error.issues[0]?.message ?? "Invalid request" }, | ||
| { status: 400 } | ||
| ); | ||
| } | ||
|
|
||
| console.error(error); | ||
| return NextResponse.json( | ||
| { message: "Internal server error" }, | ||
| { status: 500 } | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Get either a single UserLab entry by ID or a paginated list of entries. | ||
| */ | ||
| export async function GET(request: Request) { | ||
| try { | ||
| const { searchParams } = new URL(request.url); | ||
| const id = searchParams.get("id"); | ||
|
|
||
| if (id) { | ||
| const parsedId = objectIdSchema.safeParse(id); | ||
| if (!parsedId.success) { | ||
| return NextResponse.json({ message: "Invalid id" }, { status: 400 }); | ||
| } | ||
|
|
||
| const entry = await getUserLab(parsedId.data); | ||
| if (!entry) { | ||
| return NextResponse.json({ message: "UserLab not found" }, { status: 404 }); | ||
| } | ||
|
|
||
| return NextResponse.json(entry, { status: 200 }); | ||
| } | ||
|
|
||
| const pagination = paginationSchema.parse({ | ||
| page: searchParams.get("page") ?? undefined, | ||
| limit: searchParams.get("limit") ?? undefined, | ||
| }); | ||
| const entries = await getUserLabs(pagination); | ||
| return NextResponse.json(entries, { status: 200 }); | ||
| } catch (error) { | ||
| return handleRouteError(error); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Create a new UserLab entry. | ||
| */ | ||
| export async function POST(request: Request) { | ||
| try { | ||
| const body = userLabBaseSchema.parse(await request.json()); | ||
| const created = await addUserLab({ | ||
| user: body.user, | ||
| lab: body.lab, | ||
| role: body.role ?? "VIEWER", | ||
| }); | ||
|
|
||
| return NextResponse.json(created, { status: 201 }); | ||
| } catch (error) { | ||
| return handleRouteError(error); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Update an existing UserLab entry by ID. | ||
| */ | ||
| export async function PUT(request: Request) { | ||
| try { | ||
| const validator = z.object({ | ||
| id: objectIdSchema, | ||
| update: userLabUpdateSchema, | ||
| }); | ||
| const parsed = validator.parse(await request.json()); | ||
| const updated = await updateUserLab(parsed.id, parsed.update); | ||
|
|
||
| if (!updated) { | ||
| return NextResponse.json({ message: "UserLab not found" }, { status: 404 }); | ||
| } | ||
|
|
||
| return NextResponse.json(updated, { status: 200 }); | ||
| } catch (error) { | ||
| return handleRouteError(error); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Delete a UserLab entry by ID. | ||
| */ | ||
| export async function DELETE(request: Request) { | ||
| try { | ||
| const validator = z.object({ id: objectIdSchema }); | ||
| const { id } = validator.parse(await request.json()); | ||
| const deleted = await deleteUserLab(id); | ||
|
|
||
| if (!deleted) { | ||
| return NextResponse.json({ message: "UserLab not found" }, { status: 404 }); | ||
| } | ||
|
|
||
| return NextResponse.json({ message: "UserLab deleted" }, { status: 200 }); | ||
| } catch (error) { | ||
| return handleRouteError(error); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| import mongoose, { Document, Schema, Types } from "mongoose"; | ||
|
|
||
| export const userLabRoleValues = [ | ||
| "PI", | ||
| "LAB_MANAGER", | ||
| "RESEARCHER", | ||
| "VIEWER", | ||
| ] as const; | ||
|
|
||
| export type UserLabRole = (typeof userLabRoleValues)[number]; | ||
|
|
||
| export interface IUserLab extends Document { | ||
| user: Types.ObjectId; | ||
| lab: Types.ObjectId; | ||
| role: UserLabRole; | ||
| joinedAt: Date; | ||
| createdAt: Date; | ||
| updatedAt: Date; | ||
| } | ||
|
|
||
| const userLabSchema = new Schema<IUserLab>( | ||
| { | ||
| user: { | ||
| type: Schema.Types.ObjectId, | ||
| ref: "User", | ||
| required: true, | ||
| }, | ||
| lab: { | ||
| type: Schema.Types.ObjectId, | ||
| ref: "Lab", | ||
| required: true, | ||
| }, | ||
| role: { | ||
| type: String, | ||
| enum: userLabRoleValues, | ||
| default: "VIEWER", | ||
| }, | ||
| joinedAt: { | ||
| type: Date, | ||
| default: Date.now, | ||
| }, | ||
| }, | ||
| { | ||
| timestamps: true, | ||
| } | ||
| ); | ||
|
|
||
| userLabSchema.index({ user: 1, lab: 1 }, { unique: true }); | ||
|
|
||
| const UserLab = | ||
| mongoose.models.UserLab || mongoose.model<IUserLab>("UserLab", userLabSchema); | ||
|
|
||
| export default UserLab; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import { connectToDatabase } from "@/lib/mongoose"; | ||
| import { IUserLab } from "@/models/UserLab"; | ||
| import UserLab from "@/models/UserLab"; | ||
|
|
||
| export type GetUserLabsOptions = { | ||
| page: number; | ||
| limit: number; | ||
| }; | ||
|
|
||
| export type UserLabPayload = Pick<IUserLab, "user" | "lab" | "role">; | ||
|
|
||
| export async function getUserLabs({ page, limit }: GetUserLabsOptions) { | ||
| await connectToDatabase(); | ||
| const skip = (page - 1) * limit; | ||
|
|
||
| const [items, total] = await Promise.all([ | ||
| UserLab.find().skip(skip).limit(limit).populate("user").populate("lab"), | ||
| UserLab.countDocuments(), | ||
| ]); | ||
|
|
||
| return { | ||
| items, | ||
| page, | ||
| limit, | ||
| total, | ||
| totalPages: Math.ceil(total / limit) || 1, | ||
| }; | ||
| } | ||
|
|
||
| export async function getUserLab(id: string) { | ||
| await connectToDatabase(); | ||
| return UserLab.findById(id).populate("user").populate("lab"); | ||
| } | ||
|
|
||
| export async function addUserLab(data: UserLabPayload) { | ||
| await connectToDatabase(); | ||
| return UserLab.create(data); | ||
| } | ||
|
|
||
| export async function updateUserLab(id: string, update: Partial<UserLabPayload>) { | ||
| await connectToDatabase(); | ||
| return UserLab.findByIdAndUpdate(id, update, { new: true }); | ||
| } | ||
|
|
||
| export async function deleteUserLab(id: string) { | ||
| await connectToDatabase(); | ||
| return UserLab.findByIdAndDelete(id); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
for each function we need to add try catch clauses so if anything breaks it will throw an error and not break the service.. here is an example of what it would look like (would also be nice to add the comments above each one so other reading it can understand what it is doing)
/**
*/
export async function GET(request: Request, context : { params: Params }) {
try {
const parsedParams = z.object({ id: z.string().min(1) })
.safeParse(context.params);
if (!parsedParams.success) {
return NextResponse.json({ message: "Invalid ID" },
{ status: 400 });
}
const item = await getLab(parsedParams.data.id);Expand commentComment on line R40
if (!item) {
return NextResponse.json({ message: "Lab not found" },
{ status: 404 });
}
return NextResponse.json(item, { status: 200 });
} catch (err) {
console.error(err);
return NextResponse.json({ message: "Internal server error" },
{ status: 500 });
}
}