Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
f6dde51
Project cloned
MrStashy Jul 1, 2024
5cdb74d
Get all movies endpoint
MrStashy Jul 1, 2024
eef1149
Get movies with screenings
MrStashy Jul 1, 2024
5948912
Get movie by id
MrStashy Jul 1, 2024
d338522
Update movie by id
MrStashy Jul 1, 2024
649d8b2
Update customer by ID
MrStashy Jul 1, 2024
f405439
Create a screen
MrStashy Jul 1, 2024
005bbc0
Get movies with runtime limits
MrStashy Jul 1, 2024
862ece1
Reject movie POST if missing fields
MrStashy Jul 1, 2024
6515051
Throw error if adding a movie with a title that already exists in db
MrStashy Jul 1, 2024
23ede7f
Throw error if getting movie ID fails because no movie exists
MrStashy Jul 1, 2024
de3acaf
Throw errors when putting a movie with existing title, missing fields…
MrStashy Jul 1, 2024
b4c77a6
Update customer and contact simultaneously
MrStashy Jul 1, 2024
e6a0ec2
Throw error when updating a non-existant customer
MrStashy Jul 2, 2024
5dea551
Throw error when updating customer without a name
MrStashy Jul 2, 2024
64801d8
Updated Screens model to make numbers unique, added error handling fo…
MrStashy Jul 2, 2024
9c5557f
Helpers and routes for tickets
MrStashy Jul 2, 2024
d02ef6b
Create tickets
MrStashy Jul 2, 2024
d049d98
Reject ticket creation if wrong data type, no IDs found, or no IDs pr…
MrStashy Jul 2, 2024
844fc4d
Revert "Reject ticket creation if wrong data type, no IDs found, or n…
MrStashy Jul 2, 2024
4c66320
Refactored to simplify ticket data validation
MrStashy Jul 2, 2024
1d2038d
Refactored error handling for creatMovie to reduce DB calls
MrStashy Jul 2, 2024
798b853
Refactored movies controllers to reduce DB calls
MrStashy Jul 2, 2024
76d2e3c
Reviews routes and functions for get and post
MrStashy Jul 3, 2024
c4dbf5c
Fixed getMovies controller to rerturn screenings accurately
MrStashy Jul 3, 2024
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
6 changes: 0 additions & 6 deletions .env.example

This file was deleted.

9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@
"start": "npx nodemon ./src/index.js",
"test:migration": "node test/testDbMigration.js",
"test": "npx jest -i test/api/routes",
"test-extensions": "npx jest -i test/api/extensions --forceExit"
"test-extensions": "npx jest -i test/api/extensions --forceExit",
"test-movies": "npx jest -i test/api/routes/movies.spec.js",
"test-customer": "npx jest -i test/api/routes/customer.spec.js",
"test-movies-extensions": "npx jest -i test/api/extensions/movies-ext.spec.js --forceExit",
"test-customer-extensions": "npx jest -i test/api/extensions/customer-ext.spec.js --forceExit",
"test-screens-extensions": "npx jest -i test/api/extensions/screens-ext.spec.js --forceExit",
"test-tickets-extensions": "npx jest -i test/api/extensions/tickets-ext.spec.js --forceExit",
"test-reviews-extensions": "npx jest -i test/api/extensions/reviews-ext.spec.js --forceExit"
},
"prisma": {
"seed": "node prisma/seed.js"
Expand All @@ -34,6 +41,7 @@
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-async-errors": "^3.1.1",
"morgan": "^1.10.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:

- A unique constraint covering the columns `[number]` on the table `Screen` will be added. If there are existing duplicate values, this will fail.

*/
-- CreateIndex
CREATE UNIQUE INDEX "Screen_number_key" ON "Screen"("number");
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:

- A unique constraint covering the columns `[title]` on the table `Movie` will be added. If there are existing duplicate values, this will fail.

*/
-- CreateIndex
CREATE UNIQUE INDEX "Movie_title_key" ON "Movie"("title");
18 changes: 18 additions & 0 deletions prisma/migrations/20240703083007_reviews/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
-- CreateTable
CREATE TABLE "Review" (
"id" SERIAL NOT NULL,
"content" TEXT NOT NULL,
"title" VARCHAR(100) NOT NULL,
"customerId" INTEGER NOT NULL,
"movieId" INTEGER NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "Review_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "Review" ADD CONSTRAINT "Review_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "Customer"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Review" ADD CONSTRAINT "Review_movieId_fkey" FOREIGN KEY ("movieId") REFERENCES "Movie"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
20 changes: 17 additions & 3 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ model Customer {
name String
contact Contact?
tickets Ticket[]
reviews Review[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Expand All @@ -33,15 +34,16 @@ model Contact {
model Movie {
id Int @id @default(autoincrement())
screenings Screening[]
title String
title String @unique
runtimeMins Int
reviews Review[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model Screen {
id Int @id @default(autoincrement())
number Int
id Int @id @default(autoincrement())
number Int @unique
screenings Screening[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Expand All @@ -68,3 +70,15 @@ model Ticket {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model Review {
id Int @id @default(autoincrement())
content String @db.Text
title String @db.VarChar(100)
customerId Int
customer Customer @relation(fields: [customerId], references: [id])
movieId Int
movie Movie @relation(fields: [movieId], references: [id])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
74 changes: 44 additions & 30 deletions src/controllers/customer.js
Original file line number Diff line number Diff line change
@@ -1,48 +1,62 @@
const { PrismaClientKnownRequestError } = require("@prisma/client")
const { createCustomerDb } = require('../domains/customer.js')
const { PrismaClientKnownRequestError } = require("@prisma/client");
const {
createCustomerDb,
updateCustomerByIdDb,
} = require("../domains/customer.js");
const { DataNotFoundError, MissingFieldsError } = require("../errors/errors.js");

const createCustomer = async (req, res) => {
const {
name,
phone,
email
} = req.body
const { name, phone, email } = req.body;

if (!name || !phone || !email) {
return res.status(400).json({
error: "Missing fields in request body"
})
error: "Missing fields in request body",
});
}

// Try-catch is a very common way to handle errors in JavaScript.
// It allows us to customise how we want errors that are thrown to be handled.
// Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

// Here, if Prisma throws an error in the process of trying to create a new customer,
// instead of the Prisma error being thrown (and the app potentially crashing) we exit the
// `try` block (bypassing the `res.status` code) and enter the `catch` block.
try {
const createdCustomer = await createCustomerDb(name, phone, email)

res.status(201).json({ customer: createdCustomer })
const createdCustomer = await createCustomerDb(name, phone, email);
res.status(201).json({ customer: createdCustomer });
} catch (e) {
// In this catch block, we are able to specify how different Prisma errors are handled.
// Prisma throws errors with its own codes. P2002 is the error code for
// "Unique constraint failed on the {constraint}". In our case, the {constraint} is the
// email field which we have set as needing to be unique in the prisma.schema.
// To handle this, we return a custom 409 (conflict) error as a response to the client.
// Prisma error codes: https://www.prisma.io/docs/orm/reference/error-reference#common
// HTTP error codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses
if (e instanceof PrismaClientKnownRequestError) {
if (e.code === "P2002") {
return res.status(409).json({ error: "A customer with the provided email already exists" })
return res
.status(409)
.json({ error: "A customer with the provided email already exists" });
}
}

res.status(500).json({ error: e.message })
res.status(500).json({ error: e.message });
}
};

async function updateCustomerById(req, res) {
const id = Number(req.params.id);
if (isNaN(id)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Top marks

throw new DataNotFoundError('No customer found with that ID')
}

const newProps = req.body;
if (!newProps.name) {
throw new MissingFieldsError('Customers require a name')
}

try {
const customer = await updateCustomerByIdDb(id, newProps);
res.status(201).json({ customer });
} catch (e) {
if (e.code === 'P2025') {
return res.status(404).json({ error: e.message })
}
}
}

module.exports = {
createCustomer
}
createCustomer,
updateCustomerById,
};



// Prisma error codes: https://www.prisma.io/docs/orm/reference/error-reference#common
// HTTP error codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses
81 changes: 81 additions & 0 deletions src/controllers/movies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
const { PrismaClientKnownRequestError } = require("@prisma/client");
const {
getMoviesDb,
createMovieDb,
getMovieByIdDb,
updateMovieByIdDb,
getMoviesWithQueryDb,
} = require("../domains/movies.js");
const {
MissingFieldsError,
} = require("../errors/errors.js");

async function getMovies(req, res) {
let movies;
if (Object.keys(req.query).length > 0) {
movies = await getMoviesWithQueryDb(req.query);
} else {

movies = await getMoviesDb();
}
res.status(200).json({ movies });
}

async function createMovie(req, res) {
const newMovie = req.body;

const requiredFields = ["title", "runtimeMins"];
if (!requiredFields.every((field) => newMovie[field])) {
throw new MissingFieldsError("Movies require a title and runtime");
}

try {
const movie = await createMovieDb(newMovie);
res.status(201).json({ movie });
} catch (e) {
if (e.code === "P2002") {
res.status(409).json({ error: "A movie with that title already exists" });
}
}
}

async function getMovieById(req, res) {
const id = Number(req.params.id);

try {
const movie = await getMovieByIdDb(id);
res.status(200).json({ movie });
} catch (e) {
if (e.code === "P2025") {
res.status(404).json({ error: "No movie found with that ID" });
}
}
}

async function updateMovieById(req, res) {
const id = Number(req.params.id);
const updatedProps = req.body;

if (!updatedProps.title && !updatedProps.runtimeMins) {
throw new MissingFieldsError("Updating movies requires a title or runtime");
}

try {
const movie = await updateMovieByIdDb(id, updatedProps);
res.status(201).json({ movie });
} catch (e) {
if (e.code === "P2025") {
res.status(404).json({ error: "No movie found with that ID" });
}
if (e.code === "P2002") {
res.status(409).json({ error: "A movie with that title already exists" });
}
}
}

module.exports = {
getMovies,
createMovie,
getMovieById,
updateMovieById,
};
21 changes: 21 additions & 0 deletions src/controllers/reviews.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const { getAllReviewsDb, createReviewDb } = require("../domains/reviews")
const { MissingFieldsError } = require("../errors/errors")

async function getAllReviews(req, res) {
const reviews = await getAllReviewsDb()
res.status(200).json( {reviews} )
}

async function createReview(req, res) {
const { customerId, movieId, title, content } = req.body

if (!customerId || !movieId || !title || !content) {
throw new MissingFieldsError("Reviews require a customer ID, movie ID, title, and content")
}

const review = await createReviewDb(customerId, movieId, title, content )

res.status(201).json({ review })
}

module.exports = { getAllReviews, createReview }
21 changes: 21 additions & 0 deletions src/controllers/screens.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const { createScreenDb } = require('../domains/screens')
const { MissingFieldsError, DataAlreadyExistsError } = require('../errors/errors')

async function createScreen(req, res) {
const props = req.body

if (!props.number) {
throw new MissingFieldsError('All screens require a screen number')
}

try {
const screen = await createScreenDb(props)
res.status(201).json({ screen })
} catch (e) {
if (e.code === 'P2002') {
throw new DataAlreadyExistsError('There is already a screen with that number')
}
}
}

module.exports = { createScreen }
Loading