Skip to content

Commit

Permalink
Refactor db
Browse files Browse the repository at this point in the history
  • Loading branch information
anfilat committed Jul 16, 2020
1 parent 8907701 commit 54ed13f
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 42 deletions.
18 changes: 18 additions & 0 deletions db/auth.db.js
@@ -0,0 +1,18 @@
const {pool, get} = require('./core');

async function addUser(email, password) {
const sql = 'INSERT INTO "user" (email, password) VALUES ($1, $2)';
const values = [email, password];
return pool.query(sql, values);
}

async function getUser(email) {
const sql = 'SELECT * FROM "user" WHERE email = $1';
const values = [email];
return get(sql, values);
}

module.exports = {
addUser,
getUser,
};
40 changes: 40 additions & 0 deletions db/core.js
@@ -0,0 +1,40 @@
const config = require('config');
const {Pool} = require('pg');

let pool = null;

const initDb = async () => {
pool = new Pool({
connectionString: config.get('pgconnect'),
});

pool.on('error', (err) => {
console.error('Unexpected error on idle client', err);
process.exit(1);
});

const client = await pool.connect();
try {
await client.query(`CREATE TABLE IF NOT EXISTS "user" (
user_id serial PRIMARY KEY,
email VARCHAR(64),
password VARCHAR(64)
)`);
} finally {
client.release();
}
};

async function get(sql, values) {
const res = await pool.query(sql, values);
if (res.rowCount === 0) {
return null;
}
return res.rows[0];
}

module.exports = {
initDb,
pool,
get,
};
44 changes: 2 additions & 42 deletions db/index.js
@@ -1,45 +1,5 @@
const config = require('config');
const {Pool} = require('pg');

let pool;

const initDb = async () => {
pool = new Pool({
connectionString: config.get('pgconnect'),
});

pool.on('error', (err) => {
console.error('Unexpected error on idle client', err);
process.exit(1);
});

const client = await pool.connect();
try {
await client.query(`CREATE TABLE IF NOT EXISTS "user" (
user_id serial PRIMARY KEY,
email VARCHAR(64),
password VARCHAR(64)
)`);
} finally {
client.release();
}
};

async function addUser(email, password) {
const sql = 'INSERT INTO "user" (email, password) VALUES ($1, $2)';
const values = [email, password];
return pool.query(sql, values);
}

async function getUser(email) {
const sql = 'SELECT * FROM "user" WHERE email = $1';
const values = [email];
const res = await pool.query(sql, values);
if (res.rowCount === 0) {
return null;
}
return res.rows[0];
}
const {initDb} = require('./core');
const {addUser, getUser} = require('./auth.db');

module.exports = {
initDb,
Expand Down

0 comments on commit 54ed13f

Please sign in to comment.