-
Notifications
You must be signed in to change notification settings - Fork 55
/
db.js
70 lines (60 loc) · 2.14 KB
/
db.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
66
67
68
69
70
var crypto = require('crypto');
var Knex = require('knex');
var knex = Knex.initialize({
client: 'pg',
connection: process.env.HEROKU_POSTGRESQL_NAVY_URL
});
exports.findCitation = function(citation, callback) {
// Postgres JSON search based on prebuilt index
citation = escapeSQL(citation.toUpperCase());
var citationSearch = knex.raw("'{\"" + citation + "\"}'::text[] <@ (json_val_arr(citations, 'id'))");
knex('cases').where(citationSearch).select().exec(callback);
};
exports.fuzzySearch = function(str, callback) {
var parts = str.toUpperCase().split(" ");
// Search for Names
var query = knex('cases').where('defendant', 'like', '%' + parts[0] + '%');
if (parts.length > 1) query = query.andWhere('defendant', 'like', '%' + parts[1] + '%');
// Search for Citations
var citation = escapeSQL(parts[0]);
var citationSearch = knex.raw("'{\"" + citation + "\"}'::text[] <@ (json_val_arr(citations, 'id'))");
query = query.orWhere(citationSearch);
// Limit to ten results
query = query.limit(10);
query.exec(callback);
};
exports.addReminder = function(data, callback) {
var cipher = crypto.createCipher('aes256', process.env.PHONE_ENCRYPTION_KEY);
var encryptedPhone = cipher.update(data.phone, 'utf8', 'hex') + cipher.final('hex');
knex('reminders').insert({
case_id: data.caseId,
sent: false,
phone: encryptedPhone,
created_at: new Date(),
original_case: data.originalCase,
}).exec(callback);
};
exports.addQueued = function(data, callback) {
var cipher = crypto.createCipher('aes256', process.env.PHONE_ENCRYPTION_KEY);
var encryptedPhone = cipher.update(data.phone, 'utf8', 'hex') + cipher.final('hex');
knex('queued').insert({
citation_id: data.citationId,
sent: false,
phone: encryptedPhone,
created_at: new Date(),
}).exec(callback);
};
var escapeSQL = function(val) {
val.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(s) {
switch(s) {
case "\0": return "\\0";
case "\n": return "\\n";
case "\r": return "\\r";
case "\b": return "\\b";
case "\t": return "\\t";
case "\x1a": return "\\Z";
default: return "\\"+s;
}
});
return val;
};