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
34 changes: 13 additions & 21 deletions db/index.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,17 @@
// Load our .env file
require('dotenv').config()
const {Pool} = require('pg')

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

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

module.exports = client;
module.exports = pool;
75 changes: 75 additions & 0 deletions src/controllers/books.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
const pool = require('../../db')
const booksRepository = require('../repositories/booksRepository')

const types = new Map([['Fiction', "type = 'Fiction'"], ['Non-Fiction', "type = 'Non-Fiction'"]])

const getBooks = async (req, res) => {

const result = await booksRepository.getBooks(req)

res.send({ books: result.rows })
}

const createBook = async (req, res) => {
const db = await pool.connect()

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

if (
!title ||
!type ||
!author ||
!topic ||
!publication_date ||
!Number.isInteger(pages)
) {
res.status(400).json({
error: 'All fields are required and pages must be an integer.',
})
}

const result = await booksRepository.createBook(req)

res.status(201).json({ book: result.rows[0] })
}

const getBookById = async (req, res) => {
const result = await booksRepository.getBookById(req)

res.send({ book: result.rows[0] })
}

const updateBookById = async (req, res) => {
const { title, type, author, topic, publication_date, pages } = req.body

if (
!title ||
!type ||
!author ||
!topic ||
!publication_date ||
!Number.isInteger(pages)
) {
return res.status(400).json({
error: 'All fields are required and pages must be an integer.',
})
}
const result = await booksRepository.updateBookById(req)
return res.status(201).json({ book: result.rows[0] })

}

const deleteBookById = async (req, res) => {

const result = await booksRepository.deleteBookById(req)

res.status(201).send({ book: result.rows[0] })
}

module.exports = {
getBooks,
createBook,
getBookById,
deleteBookById,
updateBookById,
}
70 changes: 70 additions & 0 deletions src/controllers/pets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
const pool = require('../../db')
const petsRepository = require('../repositories/petsRepository')

const getPets = async (req, res) => {
const result = await petsRepository.getPets()

res.send({ pets: result.rows })
}

const createPet = async (req, res) => {
const { name, age, type, breed, has_microchip } = req.body

if (
!name ||
!age ||
!type ||
!breed ||
!typeof has_microchip === 'boolean'
) {
res.status(400).json({
error: 'All fields are required and has_microchip must be a boolean',
})
}

const result = await petsRepository.createPet(req)

res.status(201).json({ pet: result.rows[0] })
}

const getPetById = async (req, res) => {

const result = await petsRepository.getPetById(req)

res.send({ pet: result.rows[0] })
}

const updatePetById = async (req, res) => {
const { name, age, type, breed, has_microchip } = req.body

if (
!name ||
!age ||
!type ||
!breed ||
!typeof has_microchip === 'boolean'
) {
res.status(400).json({
error: 'All fields are required and has_microchip must be a boolean',
})
}

const result = await petsRepository.updatePetById(req)

res.status(201).json({ pet: result.rows[0] })

}

const deletePetById = async (req, res) => {
const result = await petsRepository.deletePetById(req)

res.status(201).send({ pet: result.rows[0] })
}

module.exports = {
getPets,
createPet,
getPetById,
deletePetById,
updatePetById,
}
94 changes: 94 additions & 0 deletions src/repositories/booksRepository.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
const pool = require('../../db')

const types = new Map([
['Fiction', "type = 'Fiction'"],
['Non-Fiction', "type = 'Non-Fiction'"],
])

async function getBooks(req) {
const db = await pool.connect()
const { type, topic } = req.query

const queryContents = []

let sqlQuery = 'select * from books where 1 = 1'

if (types.has(type)) {
queryContents.push(type)
sqlQuery += ` and type = $${queryContents.length}`
console.log(sqlQuery)
}

if (topic) {
queryContents.push(topic)
sqlQuery += ` and topic = $${queryContents.length}`
console.log(sqlQuery)
}

const result = await db.query(sqlQuery, queryContents)

db.release()

return result
}

async function createBook(req) {
const db = await pool.connect()
const { title, type, author, topic, publication_date, pages } = req.body

try {
const result = await db.query(
`INSERT INTO books (title, type, author, topic, publication_date, pages)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *`,
[title, type, author, topic, publication_date, pages]
)

return result
} catch (err) {
console.error('Error inserting book:', err)
} finally {
db.release()
}
}

async function getBookById(req) {
const db = await pool.connect()

const sqlQuery = 'select * from books where id = $1'
const result = await db.query(sqlQuery, [Number(req.params.id)])

db.release()

return result
}

async function updateBookById(req) {
const db = await pool.connect()
const { title, type, author, topic, publication_date, pages } = req.body

const result = await db.query(
`Update books
Set title = $1 , type = $2 , author = $3 , topic = $4 , publication_date = $5 , pages = $6
where id = $7
RETURNING *`,
[title, type, author, topic, publication_date, pages, req.params.id]
)

db.release()

return result
}

async function deleteBookById(req) {
const db = await pool.connect()

const sqlQuery = 'delete from books where id = $1 RETURNING *'
const result = await db.query(sqlQuery, [Number(req.params.id)])

db.release()

return result
}

module.exports = { getBooks, createBook, getBookById , updateBookById, deleteBookById}
77 changes: 77 additions & 0 deletions src/repositories/petsRepository.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
const pool = require('../../db')

const getPets = async () => {
const db = await pool.connect()

const sqlQuery = 'select * from pets'
const result = await db.query(sqlQuery)

db.release()

return result
}

const createPet = async (req) => {
const db = await pool.connect()

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

const result = await db.query(
`INSERT INTO pets (name, age, type, breed, has_microchip)
VALUES ($1, $2, $3, $4, $5)
RETURNING *`,
[name, age, type, breed, has_microchip]
)

db.release()

return result
}

const getPetById = async (req) => {
const db = await pool.connect()

const sqlQuery = 'select * from pets where id = $1'
const result = await db.query(sqlQuery, [Number(req.params.id)])

db.release()

return result
}

const updatePetById = async (req) => {
const db = await pool.connect()

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

const result = await db.query(
`Update pets
Set name = $1 , age = $2 , type = $3 , breed = $4 , has_microchip = $5
where id = $6
RETURNING *`,
[name, age, type, breed, has_microchip, req.params.id]
)

db.release()

return result
}

const deletePetById = async (req, res) => {
const db = await pool.connect()

const sqlQuery = 'delete from pets where id = $1 RETURNING *'
const result = await db.query(sqlQuery, [Number(req.params.id)])

db.release()

return result
}

module.exports = {
getPets,
createPet,
getPetById,
deletePetById,
updatePetById,
}
12 changes: 9 additions & 3 deletions src/routers/books.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
const express = require('express')
const router = express.Router()
const db = require("../../db");
const { getBooks, createBook, getBookById , deleteBookById, updateBookById} = require('../controllers/books')

router.get('/', async (req, res) => {
router.get('/', getBooks)

})
router.post('/', createBook)

router.get('/:id', getBookById)

router.delete('/:id', deleteBookById)

router.put('/:id', updateBookById)

module.exports = router
15 changes: 15 additions & 0 deletions src/routers/pets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const express = require('express')
const router = express.Router()
const { getPets, createPet, getPetById , deletePetById, updatePetById} = require('../controllers/pets')

router.get('/', getPets)

router.post('/', createPet)

router.get('/:id', getPetById)

router.delete('/:id', deletePetById)

router.put('/:id', updatePetById)

module.exports = router
Loading