Skip to content
Open
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
1 change: 0 additions & 1 deletion .env.example

This file was deleted.

38 changes: 16 additions & 22 deletions db/index.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,19 @@
// Load our .env file
require('dotenv').config()

// Require Client obj from the postgres node module
const { Client } = require("pg");
const { Pool } = require('pg');

const { PGHOST, PGDATABASE, PGUSER, PGPASSWORD } = process.env;

const dbConnection = new Pool({
host: PGHOST,
database: PGDATABASE,
username: PGUSER,
password: PGPASSWORD,
port: 5432,
ssl: {
require: true,
},
})

module.exports = dbConnection

const client = {
query: async (str, values) => {
// Get the connection string from process.env -
// the dotenv library sets this variable based
// on the contents of our env file
// Create a new connection to the database using the Client
// object provided by the postgres node module
const dbClient = new Client(process.env.PGURL)
// connect a connection
await dbClient.connect()
// execute the query
const result = await dbClient.query(str, values)
// close the connection
await dbClient.end()
return result
}
}

module.exports = client;
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.

8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,19 @@
"scripts": {
"start": "npx nodemon src/index.js",
"test": "npx jest -i test/api/routes --forceExit",
"test-extensions": "npx jest -i test/api/extensions --forceExit"
"test-extensions": "npx jest -i test/api/extensions --forceExit",
"test-books": "npx jest -i test/api/routes/books.spec.js --forceExit",
"test-books-extensions": "npx jest -i test/api/extensions/books.spec.js --forceExit",
"test-pets": "npx jest -i test/api/routes/pets.spec.js --forceExit",
"test-pets-extensions": "npx jest -i test/api/extensions/pets.spec.js --forceExit",
"test-breeds-extensions": "npx jest -i test/api/extensions/breeds.spec.js --forceExit"
},
"dependencies": {
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-async-errors": "^3.1.1",
"faker": "^5.5.3",
"morgan": "1.10.0",
"pg": "8.6.0",
Expand Down
104 changes: 104 additions & 0 deletions src/controllers/booksControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
const {
MissingFieldsError,
NoDataError,
InvalidParameterError,
DataAlreadyExistsError,
} = require("../errors/errors");
const {
fetchAllBooks,
postBook,
fetchBookById,
updateBookById,
deleteBookById,
fetchBookByQuery,
} = require("../dal/bookRepository");

async function getBooksController(req, res) {
let books;
const query = req.query;

if (query) {
if (query.perPage < 10 || query.perPage > 50) {
throw new InvalidParameterError(
`parameter invalid perPage: ${query.perPage} not valid. Accepted range is 10 - 50`
);
}
books = await fetchBookByQuery(query);
} else {
books = await fetchAllBooks();
}

res
.status(200)
.json({ books, page: Number(query.page), per_page: Number(query.perPage) });
}

async function addBookController(req, res) {
const newBook = req.body;
const requiredProperties = [
"title",
"type",
"author",
"topic",
"publication_date",
"pages",
];
const allFieldsExist = requiredProperties.every(
(property) => newBook[property]
);
if (!allFieldsExist) {
throw new MissingFieldsError(
"Books require a title, type, author, topic, publication year, and number of pages"
);
}
const book = await postBook(newBook);
res.status(201).json({ book });
}

async function getBookByIdController(req, res) {
targetBookId = Number(req.params.id);

const book = await fetchBookById(targetBookId);
if (!book) {
throw new NoDataError(`no book with id: ${targetBookId}`);
}
res.status(200).json({ book });
}

async function putBookByIdController(req, res, next) {
const targetBookId = Number(req.params.id);
const newParams = req.body;

const allBooks = await fetchAllBooks();
if (allBooks.find((book) => book.title === newParams.title)) {
throw new DataAlreadyExistsError(
`A book with the title: ${newParams.title} already exists`
);
}

const book = await fetchBookById(targetBookId);
if (!book) {
throw new NoDataError(`no book with id: ${targetBookId}`);
}
const updatedBook = await updateBookById(targetBookId, newParams);
res.status(201).json({ book: updatedBook });
}

async function deleteBookByIdController(req, res, next) {
const targetBookId = Number(req.params.id);

const book = await fetchBookById(targetBookId);
if (!book) {
throw new NoDataError(`no book with id: ${targetBookId}`);
}
const deletedBook = await deleteBookById(targetBookId);
res.status(201).json({ book: deletedBook });
}

module.exports = {
addBookController,
getBooksController,
getBookByIdController,
putBookByIdController,
deleteBookByIdController,
};
9 changes: 9 additions & 0 deletions src/controllers/breedsControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const { fetchBreeds } = require("../dal/breedsRepository");

async function getAllBreedsController(req, res) {
const breeds = await fetchBreeds(req.query);
console.log({ breeds })
res.status(200).json({ breeds });
}

module.exports = { getAllBreedsController };
94 changes: 94 additions & 0 deletions src/controllers/petsControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
const { MissingFieldsError, NoDataError, InvalidParameterError } = require("../errors/errors");

const {
fetchAllPets,
fetchPetById,
updatePetById,
addPet,
deletePet,
fetchPetsWithQuery,
} = require("../dal/petsRepository");

async function getPetsController(req, res) {
let pets;

if (req.query) {
if (req.query.perPage < 10 || req.query.perPage > 50) {
throw new InvalidParameterError(`parameter invalid perPage: ${req.query.perPage} not valid. Accepted range is 10 - 50`)
}
pets = await fetchPetsWithQuery(req.query);
} else {
pets = await fetchAllPets();
}

res
.status(200)
.json({
pets,
page: Number(req.query.page),
per_page: Number(req.query.perPage),
});
}

async function getPetsByIdController(req, res) {
const id = Number(req.params.id);
const pet = await fetchPetById(id);

if (!pet) {
throw new NoDataError(`no pet with id: ${id}`);
}
res.status(200).json({ pet });
}

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

const found = await fetchPetById(id)
if (!found) {
throw new NoDataError(`no pet with id: ${id}`);
}

const pet = await updatePetById(id, updatedParams);
res.status(201).json({ pet });
}

async function addPetController(req, res) {
const newPet = req.body;

const requiredFields = ["name", "age", "type", "breed", "has_microchip"];
const missingFields = [];
requiredFields.forEach((field) => {
if (!newPet[field]) {
missingFields.push(field);
}
});
if (missingFields.length > 0) {
throw new MissingFieldsError(
`missing fields: ${missingFields.toString().replaceAll(",", ", ")}`
);
}

const pet = await addPet(newPet);
res.status(201).json({ pet });
}

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

const found = await fetchPetById(id)
if (!found) {
throw new NoDataError(`no pet with id: ${id}`);
}

const pet = await deletePet(id);
res.status(201).json({ pet });
}

module.exports = {
getPetsController,
getPetsByIdController,
updatePetByIdController,
addPetController,
deletePetController,
};
101 changes: 101 additions & 0 deletions src/dal/bookRepository.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
const db = require("../../db/index.js");

async function fetchAllBooks() {
try {
const result = await db.query("SELECT * FROM books");
return result.rows;
} catch (e) {
console.log(e);
}
}

async function fetchBookByQuery(query) {
let sqlQuery = "SELECT * FROM books";
const params = [];
const perPage = query.perPage || 20;

if (query.author) {
params.push(query.author);
sqlQuery += ` WHERE author = $${params.length}`;
}

params.push(perPage);
sqlQuery += ` LIMIT $${params.length}`;

if (query.page) {
params.push((query.page - 1) * query.perPage);
sqlQuery += ` OFFSET $${params.length}`;
}

try {
const result = await db.query(sqlQuery, params);
return result.rows;
} catch (e) {
console.log(e);
}
}

async function postBook(book) {
try {
const sqlQuery = `INSERT INTO books (title, type, author, topic, publication_date, pages) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *;`;
const result = await db.query(sqlQuery, [
book.title,
book.type,
book.author,
book.topic,
book.publication_date,
book.pages,
]);
return result.rows[0];
} catch (e) {
console.log(e);
}
}

async function fetchBookById(id) {
try {
const sqlQuery = "SELECT * FROM books WHERE id = $1;";
const result = await db.query(sqlQuery, [id]);
return result.rows[0];
} catch (e) {
console.log(e);
}
}

async function updateBookById(id, newParams) {
try {
const sqlQuery =
"UPDATE books SET title = $2, type = $3, author = $4, topic = $5, publication_date = $6, pages = $7 WHERE id = $1 RETURNING *;";
const result = await db.query(sqlQuery, [
id,
newParams.title,
newParams.type,
newParams.author,
newParams.topic,
newParams.publication_date,
newParams.pages,
]);
return result.rows[0];
} catch (e) {
console.log(e);
}
}

async function deleteBookById(id) {
try {
const sqlQuery = "DELETE FROM books WHERE id = $1 RETURNING *;";
const result = await db.query(sqlQuery, [id]);
return result.rows[0];
} catch (e) {
console.log(e);
}
}

module.exports = {
fetchAllBooks,
postBook,
fetchBookById,
updateBookById,
deleteBookById,
fetchBookByQuery,
};
Loading