Skip to content

separate routes and db config files #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
18 changes: 18 additions & 0 deletions config/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@


let pg = require('pg');

let pool = new pg.Pool({
user: 'me',
host: 'localhost',
database: 'api',
password: 'password',
port: 5432,
}, async (err) => {
if (!err) {
console.log('db ok');
}
});


module.exports = pool;
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./queries')
const db = require('./routes/queries')
const port = 3000

app.use(bodyParser.json())
Expand Down
22 changes: 7 additions & 15 deletions queries.js → routes/queries.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
const Pool = require('pg').Pool
const pool = new Pool({
user: 'me',
host: 'localhost',
database: 'api',
password: 'password',
port: 5432,
})

let pool = require('../config/db');
const getUsers = (request, response) => {
pool.query('SELECT * FROM users ORDER BY id ASC', (error, results) => {
if (error) {
Expand Down Expand Up @@ -34,7 +26,7 @@ const createUser = (request, response) => {
if (error) {
throw error
} else if (!Array.isArray(results.rows) || results.rows.length < 1) {
throw error
throw error
}
response.status(201).send(`User added with ID: ${results.rows[0].id}`)
})
Expand All @@ -50,15 +42,15 @@ const updateUser = (request, response) => {
(error, results) => {
if (error) {
throw error
}
}
if (typeof results.rows == 'undefined') {
response.status(404).send(`Resource not found`);
response.status(404).send(`Resource not found`);
} else if (Array.isArray(results.rows) && results.rows.length < 1) {
response.status(404).send(`User not found`);
response.status(404).send(`User not found`);
} else {
response.status(200).send(`User modified with ID: ${results.rows[0].id}`)
response.status(200).send(`User modified with ID: ${results.rows[0].id}`)
}

}
)
}
Expand Down