-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
65 lines (51 loc) · 1.7 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
'use strict'
const Redshift = require('node-redshift')
const path = require('path')
const fs = require('fs')
const vm = require('vm')
/**
* Class for querying Redshift easily
*/
class RedshiftQuery {
/**
* Initializes a RedshiftQuery class
* @param {Object} opts Configuration for the class
*/
constructor(opts) {
this.queryPath = opts.queryPath
this.redshift = new Redshift(opts.connection)
}
/**
* Queries a Redshift instance from the given file and parameters
* @param {String} sqlFile Name of the file containing the query
* @param {Object} params Object that contains parameters
* @return {Array[Row]} Array of results (underlying library is pg so the format will be the same)
*/
queryByFile(sqlFile, params) {
// Create a fully-qualified path to the desired file
const sqlPath = path.resolve(this.queryPath, sqlFile)
// Read from the file and cast it to a string
let query = fs.readFileSync(sqlPath).toString()
// Make the query a template string and eval it with
// the given parameters.
query = vm.runInNewContext('`' + query + '`', params)
return this.queryByString(query)
}
/**
* Queries a Redshift instance from the given query string
* @param {String} query Redshift query
* @return {Array[Row]} Array of results (underlying library is pg so the format will be the same)
*/
queryByString(query) {
return new Promise((resolve, reject) => {
// Execute the query and resolve the promise accordingly
this.redshift.query(query, (err, data) => {
if (err) {
return reject(err)
}
return resolve(data)
})
})
}
}
module.exports = RedshiftQuery