-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
47 lines (42 loc) · 1.67 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Import the Movies functions
import { ObjectId } from "mongodb";
import MovieController from "./controllers/movies.ts";
import type { Movie } from "./models/movies.ts";
const server = Bun.serve({
async fetch(req) {
const url = new URL(req.url);
const method = req.method;
if (url.pathname === "/") return new Response("Welcome to the movie database");
// Routes for the API
let moviesRoutes = new RegExp(/^\/movies\/?(.*)/);
const movies = new MovieController();
// POST /movies
if (url.pathname.match(moviesRoutes) && method === "POST") {
const movie: Movie = await req.json();
return Response.json(await movies.addMovie(movie));
}
// GET /movies and GET /movies/:id
if (url.pathname.match(moviesRoutes) && method === "GET") {
const routeParams = url.pathname.split("/");
if (routeParams[2]) {
const movieId: ObjectId = new ObjectId(routeParams[2]);
return Response.json(await movies.getMovieById(movieId));
} else {
return Response.json(await movies.getMovies());
}
}
// PUT /movies/:id
if (url.pathname.match(moviesRoutes) && method === "PUT") {
const movieId: ObjectId = new ObjectId(url.pathname.split("/")[2]);
const movie: Movie = await req.json();
return Response.json(await movies.updateMovie(movieId, movie));
}
// DELETE /movies/:id
if (url.pathname.match(moviesRoutes) && method === "DELETE") {
const movieId: ObjectId = new ObjectId(url.pathname.split("/")[2]);
return Response.json(await movies.deleteMovie(movieId));
}
return new Response("404!");
},
});
console.log(`Listening on http://localhost:${server.port} ...`);