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.

37 changes: 15 additions & 22 deletions db/index.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
// Load our .env file
require('dotenv').config()
// import Pool from Postgres
const { Pool } = require("pg");

// Require Client obj from the postgres node module
const { Client } = require("pg");
// import environment variables from .env file
const { PGHOST, PGDATABASE, PGUSER, PGPASSWORD } = process.env;

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
}
}
const dbConnection = new Pool({
host: PGHOST,
database: PGDATABASE,
username: PGUSER,
password: PGPASSWORD,
port: 5432,
ssl: {
require: true,
},
});

module.exports = client;
module.exports = dbConnection;
58 changes: 58 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"dotenv": "^16.3.1",
"express": "^4.18.2",
"faker": "^5.5.3",
"joi": "^13.1.0",
"morgan": "1.10.0",
"pg": "8.6.0",
"pg-promise": "^11.5.4"
Expand Down
10 changes: 9 additions & 1 deletion sql/create-books.sql
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ CREATE TABLE IF NOT EXISTS books (
type VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
topic VARCHAR(255) NOT NULL,
publication_date DATE NOT NULL,
publication_date VARCHAR(255) NOT NULL, -- *
pages INTEGER NOT NULL
);

--* Using DATE data type constraint makes a problem with the test as the data returned from the database base is different from the data sent, so that I always get this error message:

-- Expected: "2020-11-17T00:00:00.000Z"
-- Received: "2020-11-16T23:00:00.000Z"

-- I don't know why. But I thibk that there is a special processing for the DATE type from DBMS. The only way to solve this problem was to change the data type from DATE to VARCHAR.

116 changes: 116 additions & 0 deletions src/controllers/booksController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
const Joi = require("joi");
const dbConnection = require("../../db/index.js");
const queries = require("../queries/booksQueries.js");

// HELPER FUNCTIONS
function validateBook(req, res) {
const schema = {
title: Joi.string().required(),
type: Joi.string().required(),
author: Joi.string().required(),
topic: Joi.string().required(),
publication_date: Joi.string().required(),
pages: Joi.number().required(),
};

return Joi.validate(req.body, schema);
}

// CONTROLLER FUNCTIONS
exports.getAllBooks = (req, res) => {
dbConnection.query(queries.getAllBooks, (error, result) => {
if (error) throw error;
res.status(200).json({ books: result.rows });
});
};

exports.getBook = (req, res) => {
const id = Number.parseInt(req.params.id, 10);

dbConnection.query(queries.getBookById, [id], (error, result) => {
if (error) throw error;

const [book] = result.rows;
if (!book) {
return res.status(404).json({
message: `Book with id ${id} does not exist in the database`,
});
}
res.status(200).json({ book });
});
};

exports.addBook = (req, res) => {
// to validate book's schema
const { error } = validateBook(req, res);
if (error) return res.status(400).send(error.details[0].message);

const { title, type, author, topic, publication_date, pages } = req.body;

dbConnection.query(
queries.addBook,
[title, type, author, topic, publication_date, pages],
(error, result) => {
if (error) throw error;
// to get the new added book and send it to the user
dbConnection.query(queries.getAllBooks, (error, result) => {
if (error) throw error;
res.status(201).json({ book: result.rows[result.rows.length - 1] });
});
}
);
};

exports.deleteBook = (req, res) => {
const id = Number.parseInt(req.params.id, 10);
// check if the book exists
dbConnection.query(queries.getBookById, [id], (error, result) => {
const book = result.rows;
const noBookFound = !book.length;
// if it does not exist send an error message
if (noBookFound) {
return res.status(404).json({
message: `Book with id ${id} does not exist in the database`,
});
}
// if it exists, delete it and send it to the user
dbConnection.query(queries.deleteBookById, [id], (error, result) => {
if (error) throw error;
res.status(201).json({ book: book[0] });
});
});
};

exports.updateBook = (req, res) => {
// to validate book's schema
const { error } = validateBook(req, res);
if (error) return res.status(400).send(error.details[0].message);

const id = Number.parseInt(req.params.id, 10);
// check if the book exists
dbConnection.query(queries.getBookById, [id], (error, result) => {
const noBookFound = !result.rows.length;
// if it does not exist send an error message
if (noBookFound) {
return res.status(404).json({
message: `Book with id ${id} does not exist in the database`,
});
}
// if it exists, update it
const { title, type, author, topic, publication_date, pages } = req.body;
dbConnection.query(
queries.updateBookById,
[title, type, author, topic, publication_date, pages, id],
(error, result) => {
if (error) throw error;
// get the updated book and send it to the user
dbConnection.query(queries.getBookById, [id], (error, result) => {
if (error) throw error;

const [book] = result.rows;
res.status(201).json({ book });
});
}
);
});
};
115 changes: 115 additions & 0 deletions src/controllers/petsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
const Joi = require("joi");
const dbConnection = require("../../db/index.js");
const queries = require("../queries/petsQueries.js");

// HELPER FUNCTIONS
function validatePet(req, res) {
const schema = {
name: Joi.string().required(),
age: Joi.required(),
type: Joi.string().required(),
breed: Joi.string().required(),
has_microchip: Joi.boolean().required(),
};

return Joi.validate(req.body, schema);
}

// CONTROLLER FUNCTIONS
exports.getAllPets = (req, res) => {
dbConnection.query(queries.getAllPets, (error, result) => {
if (error) throw error;
res.status(200).json({ pets: result.rows });
});
};

exports.getPet = (req, res) => {
const id = Number.parseInt(req.params.id, 10);

dbConnection.query(queries.getPetById, [id], (error, result) => {
if (error) throw error;

const [pet] = result.rows;
if (!pet) {
return res.status(404).json({
message: `Pet with id ${id} does not exist in the database`,
});
}
res.status(200).json({ pet });
});
};

exports.addPet = (req, res) => {
// to validate pet's schema
const { error } = validatePet(req, res);
if (error) return res.status(400).send(error.details[0].message);

const { name, age, type, breed, has_microchip } = req.body;

dbConnection.query(
queries.addPet,
[name, age, type, breed, has_microchip],
(error, result) => {
if (error) throw error;
// to get the new added pet and send it to the user
dbConnection.query(queries.getAllPets, (error, result) => {
if (error) throw error;
res.status(201).json({ pet: result.rows[result.rows.length - 1] });
});
}
);
};

exports.deletePet = (req, res) => {
const id = Number.parseInt(req.params.id, 10);
// check if the pet exists
dbConnection.query(queries.getPetById, [id], (error, result) => {
const pet = result.rows;
const noPetFound = !pet.length;
// if it does not exist send an error message
if (noPetFound) {
return res.status(404).json({
message: `Pet with id ${id} does not exist in the database`,
});
}
// if it exists, delete it and send it to the user
dbConnection.query(queries.deletePetById, [id], (error, result) => {
if (error) throw error;
res.status(201).json({ pet: pet[0] });
});
});
};

exports.updatePet = (req, res) => {
// to validate pet's schema
const { error } = validatePet(req, res);
if (error) return res.status(400).send(error.details[0].message);

const id = Number.parseInt(req.params.id, 10);
// check if the pet exists
dbConnection.query(queries.getPetById, [id], (error, result) => {
const noPetFound = !result.rows.length;
// if it does not exist send an error message
if (noPetFound) {
return res.status(404).json({
message: `Pet with id ${id} does not exist in the database`,
});
}
// if it exists, update it
const { name, age, type, breed, has_microchip } = req.body;
dbConnection.query(
queries.updatePetById,
[name, age, type, breed, has_microchip, id],
(error, result) => {
if (error) throw error;
// get the updated pet and send it to the user
dbConnection.query(queries.getPetById, [id], (error, result) => {
if (error) throw error;

const [pet] = result.rows;
res.status(201).json({ pet });
});
}
);
});
};
Loading