Skip to content
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

Events crud #144

Merged
merged 6 commits into from
Nov 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions app/(api)/_datalib/events/createEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { getDatabase } from '@utils/mongodb/mongoClient.mjs';
import parseAndReplace from '@utils/request/parseAndReplace';
import {
DuplicateError,
HttpError,
NoContentError,
} from '@utils/response/Errors';
import isBodyEmpty from '@utils/request/isBodyEmpty';

export async function createEvent(body: object) {
try {
if (isBodyEmpty(body)) {
throw new NoContentError();
}
const parsedBody = await parseAndReplace(body);
const db = await getDatabase();

//duplicate event
const existingEvent = await db.collection('events').findOne({
name: parsedBody.name,
});
if (existingEvent) {
throw new DuplicateError('Duplicate: event already exists.');
}

const creationStatus = await db.collection('events').insertOne(parsedBody);

JayJ104 marked this conversation as resolved.
Show resolved Hide resolved
const createdEvent = await db.collection('events').findOne({
_id: creationStatus.insertedId,
});

if (!createdEvent) {
throw new HttpError('Failed to fetch the created item');
}

return { ok: true, body: createdEvent, error: null };
} catch (e) {
const error = e as HttpError;
return {
ok: false,
body: null,
error: error.message || 'Internal Server Error',
};
}
}
33 changes: 33 additions & 0 deletions app/(api)/_datalib/events/deleteEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { getDatabase } from '@utils/mongodb/mongoClient.mjs';
import { HttpError, NotFoundError } from '@utils/response/Errors';
import { ObjectId } from 'mongodb';

export async function deleteEvent(id: string) {
try {
const db = await getDatabase();
const objectId = ObjectId.createFromHexString(id);

const deletion = await db.collection('events').deleteOne({
_id: objectId,
});

if (deletion.deletedCount === 0) {
throw new NotFoundError(
`Could not delete event with ID: '${id}'. Event does not exist or ID is incorrect.`
);
}

return {
ok: true,
body: 'Event deleted.',
error: null,
};
} catch (e) {
const error = e as HttpError;
return {
ok: false,
body: null,
error: error.message || 'Internal Server Error',
};
}
}
57 changes: 57 additions & 0 deletions app/(api)/_datalib/events/getEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { getDatabase } from '@utils/mongodb/mongoClient.mjs';
import { HttpError, NotFoundError } from '@utils/response/Errors';
import { ObjectId } from 'mongodb';

/**
* Retrieves an event from the database by id
* @param query - ID of Event
* @returns: {
* ok: boolean,
* body: object | null,
* error: number | null
* }
*/
export async function getEvent(id: string) {
try {
const db = await getDatabase();
const objectId = ObjectId.createFromHexString(id);
const event = await db.collection('events').findOne({ _id: objectId });

if (!event) {
throw new NotFoundError(`Event with id: ${id} not found.`);
}

return {
ok: true,
body: event,
error: null,
};
} catch (e) {
const error = e as HttpError;
return {
ok: false,
body: null,
error: error.message,
};
}
}

export async function getEvents(query: object) {
try {
const db = await getDatabase();
const events = await db.collection('events').find(query).toArray();

return {
ok: true,
body: events,
error: null,
};
} catch (e) {
const error = e as HttpError;
return {
ok: false,
body: null,
error: error.message || 'Internal Server Error',
};
}
}
44 changes: 44 additions & 0 deletions app/(api)/_datalib/events/updateEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { getDatabase } from '@utils/mongodb/mongoClient.mjs';
import { ObjectId } from 'mongodb';
import isBodyEmpty from '@utils/request/isBodyEmpty';
import parseAndReplace from '@utils/request/parseAndReplace';
import {
HttpError,
NoContentError,
NotFoundError,
} from '@utils/response/Errors';

export async function updateEvent(id: string, body: object) {
try {
if (isBodyEmpty(body)) {
throw new NoContentError();
}

const db = await getDatabase();
const objectId = ObjectId.createFromHexString(id);
const parsedBody = await parseAndReplace(body);

const event = await db
.collection('users')
.updateOne({ _id: objectId }, parsedBody);

if (event.matchedCount === 0) {
throw new NotFoundError(
`Could not update event with ID: '${id}'. Event does not exist or ID is incorrect.`
);
}

return {
ok: true,
body: event,
error: null,
};
} catch (e) {
const error = e as HttpError;
return {
ok: false,
body: null,
error: error.message || 'Internal Server Error',
};
}
}
10 changes: 10 additions & 0 deletions app/(api)/api/events/[id]/delete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { NextRequest, NextResponse } from 'next/server';
import { deleteEvent } from '@datalib/events/deleteEvent';

export async function DELETE(
_: NextRequest,
{ params }: { params: { id: string } }
) {
const res = await deleteEvent(params.id);
return NextResponse.json({ ...res }, { status: res.ok ? 200 : 500 });
}
10 changes: 10 additions & 0 deletions app/(api)/api/events/[id]/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { NextRequest, NextResponse } from 'next/server';
import { getEvent } from '@datalib/events/getEvent';

export async function GET(
_: NextRequest,
{ params }: { params: { id: string } }
) {
const res = await getEvent(params.id);
return NextResponse.json({ ...res }, { status: res.ok ? 200 : 500 });
}
11 changes: 11 additions & 0 deletions app/(api)/api/events/[id]/put.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { NextRequest, NextResponse } from 'next/server';
import { updateEvent } from '@datalib/events/updateEvent';

export async function PUT(
request: NextRequest,
{ params }: { params: { id: string } }
) {
const body = await request.json();
const res = await updateEvent(params.id, body);
return NextResponse.json({ ...res }, { status: res.ok ? 200 : 500 });
}
10 changes: 10 additions & 0 deletions app/(api)/api/events/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import authenticated from '@utils/authentication/authenticated';
import { PUT as put } from './put';
import { GET as get } from './get';
import { DELETE as del } from './delete';

const PUT = authenticated(put);
const GET = authenticated(get);
const DELETE = authenticated(del);

export { PUT, GET, DELETE };
9 changes: 9 additions & 0 deletions app/(api)/api/events/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { NextRequest, NextResponse } from 'next/server';
import { getEvents } from '@datalib/events/getEvent';
import getQueries from '@utils/request/getQueries';

export async function GET(request: NextRequest) {
const queries = await getQueries(request, 'events');
const res = await getEvents(queries);
return NextResponse.json({ ...res }, { status: res.ok ? 200 : 500 });
}
8 changes: 8 additions & 0 deletions app/(api)/api/events/post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { NextRequest, NextResponse } from 'next/server';
import { createEvent } from '@datalib/events/createEvent';

export async function POST(request: NextRequest) {
const body = await request.json();
const res = await createEvent(body);
return NextResponse.json({ ...res }, { status: res.ok ? 200 : 500 });
}
8 changes: 8 additions & 0 deletions app/(api)/api/events/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import authenticated from '@utils/authentication/authenticated';
import { POST as post } from './post';
import { GET as get } from './get';

const POST = authenticated(post);
const GET = authenticated(get);

export { POST, GET };
12 changes: 12 additions & 0 deletions app/_types/event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
interface EventInt {
_id: string;
name: string;
host?: string;
type: string;
location: string;
star_time: Date;
end_time: Date;
tags?: string[];
}

export default EventInt;