Skip to content

Commit 03e36b4

Browse files
author
Peter Svetlichny
committed
refactor(index): general clean-up and refactoring
1 parent ef6b8de commit 03e36b4

File tree

1 file changed

+57
-86
lines changed

1 file changed

+57
-86
lines changed

src/index.js

Lines changed: 57 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
1-
import Promise from 'bluebird';
2-
import pg from 'pg';
1+
const Promise = require('bluebird')
2+
const pg = require('pg')
33

44
/**
55
* @class postgres
66
*/
7-
export default class {
7+
module.exports = class {
88
/**
99
* Creates the connection string for the instance
1010
* @param {Object} config
11-
* @property {String} config.host The host to connect to
12-
* @property {String} config.username The connection username
13-
* @property {String} config.password The connection password
14-
* @property {String} config.database The connection database
11+
* @param {String} config.host The host to connect to
12+
* @param {String} config.user The connection username
13+
* @param {String} config.password The connection password
14+
* @param {String} config.database The connection database
1515
*/
1616
constructor (config) {
17-
this.connStr = `postgres://${config.username}:${config.password}@${config.host}/${config.database}`;
17+
this.pg = new pg.Client(config)
1818
}
1919

2020
/**
@@ -23,24 +23,18 @@ export default class {
2323
* @returns {Object} promise
2424
*/
2525
query (query) {
26-
return new Promise((resolve, reject) => {
27-
pg.connect(this.connStr, (err, client, done) => {
28-
if (err) {
29-
reject(err);
30-
} else {
31-
client.query(query, (e, result) => {
32-
// Release client
33-
done();
34-
// Process
35-
if (e) {
36-
reject(e);
37-
} else {
38-
resolve(result);
39-
}
40-
});
41-
}
42-
});
43-
});
26+
let res
27+
return this.pg.connect()
28+
.then(() => this.pg.query(query))
29+
.then(data => {
30+
res = data
31+
return this.pg.end()
32+
})
33+
.then(() => res)
34+
.catch((err) => {
35+
return this.pg.end()
36+
.then(() => { throw err })
37+
})
4438
}
4539

4640
/**
@@ -51,17 +45,17 @@ export default class {
5145
*/
5246
createTable (props) {
5347
// Build query
54-
const len = Object.keys(props).length;
55-
let i = 1;
56-
let query = `CREATE TABLE IF NOT EXISTS ${this.tableName} (`;
48+
const len = Object.keys(props).length
49+
let i = 1
50+
let query = `CREATE TABLE IF NOT EXISTS ${this.tableName} (`
5751
for (let prop in props) {
58-
let comma = (i !== len) ? ', ' : '';
59-
query += `${prop} ${props[prop].join(' ')}${comma}`;
60-
i++;
52+
let comma = (i !== len) ? ', ' : ''
53+
query += `${prop} ${props[prop].join(' ')}${comma}`
54+
i++
6155
}
62-
query += ');';
56+
query += ')'
6357
// Run query
64-
return this.query(query);
58+
return this.query(query)
6559
}
6660

6761
/**
@@ -71,24 +65,17 @@ export default class {
7165
* @returns {Object} promise
7266
*/
7367
create (body, version = false) {
74-
return new Promise((resolve, reject) => {
75-
// Validate
76-
const validationErrors = this.validate(body, version);
77-
if (validationErrors) {
78-
reject(validationErrors);
79-
} else {
80-
// Build query
81-
let cols = [];
82-
let vals = [];
83-
for (let prop in body) {
84-
cols.push(prop);
85-
vals.push('\'' + body[prop] + '\'');
86-
}
87-
const query = `INSERT INTO ${this.tableName} (${cols.join(',')}) VALUES (${vals.join(',')});`;
88-
// Run query
89-
resolve(this.query(query));
90-
}
91-
});
68+
return this.validate(body)
69+
.then(data => {
70+
const vals = []
71+
const cols = Object.keys(data).reduce((acc, key) => {
72+
vals.push(`'${data[key]}'`)
73+
acc.push(key)
74+
return acc
75+
}, [])
76+
const query = `INSERT INTO ${this.tableName} (${cols.join(',')}) VALUES (${vals.join(',')})`
77+
return this.query(query)
78+
})
9279
}
9380

9481
/**
@@ -97,25 +84,13 @@ export default class {
9784
* @returns {Object} promise
9885
*/
9986
read (query, version = false) {
100-
let where;
101-
if (query) {
102-
where = ` WHERE ${query}`;
103-
} else {
104-
where = '';
105-
}
106-
return new Promise((resolve, reject) => {
107-
return this.query(`SELECT * FROM ${this.tableName}${where}`)
108-
.then((results) => {
109-
let tmp = [];
110-
results.rows.forEach((r) => {
111-
tmp.push(this.sanitize(r, version));
112-
});
113-
resolve(tmp);
87+
const where = query ? ` WHERE ${query}` : ''
88+
return this.query(`SELECT * FROM ${this.tableName}${where}`)
89+
.then((results) => {
90+
return results.rows.map((r) => {
91+
return this.sanitize ? this.sanitize(r, version) : r
11492
})
115-
.catch((err) => {
116-
reject(err);
117-
});
118-
});
93+
})
11994
}
12095

12196
/**
@@ -126,24 +101,20 @@ export default class {
126101
* @returns {Object} promise
127102
*/
128103
update (query, body, version = false) {
129-
return new Promise((resolve, reject) => {
130-
const validationErrors = this.validate(body, version);
131-
if (validationErrors) {
132-
reject(validationErrors);
133-
} else {
134-
let i = 1;
135-
let changes = '';
136-
let len = Object.keys(body).length;
104+
return this.validate(body)
105+
.then(data => {
106+
let i = 1
107+
let changes = ''
108+
let len = Object.keys(body).length
137109
for (let prop in body) {
138110
if ({}.hasOwnProperty.call(body, prop)) {
139-
let comma = (i !== len) ? ', ' : '';
140-
changes += `${prop}='${body[prop]}'${comma}`;
141-
i++;
111+
let comma = (i !== len) ? ', ' : ''
112+
changes += `${prop}='${body[prop]}'${comma}`
113+
i++
142114
}
143115
}
144-
resolve(this.query(`UPDATE ${this.tableName} SET ${changes} WHERE ${query}`));
145-
}
146-
});
116+
return this.query(`UPDATE ${this.tableName} SET ${changes} WHERE ${query}`)
117+
})
147118
}
148119

149120
/**
@@ -152,7 +123,7 @@ export default class {
152123
* @returns {Object} promise
153124
*/
154125
delete (query) {
155-
return this.query(`DELETE FROM ${this.tableName} WHERE ${query}`);
126+
return this.query(`DELETE FROM ${this.tableName} WHERE ${query}`)
156127
}
157128

158129
/**
@@ -161,7 +132,7 @@ export default class {
161132
* @param {Function} fn The function to extend on the object
162133
*/
163134
extend (name, fn) {
164-
this[name] = fn.bind(this);
135+
this[name] = fn.bind(this)
165136
}
166137

167138
}

0 commit comments

Comments
 (0)