-
Notifications
You must be signed in to change notification settings - Fork 71
/
index.js
102 lines (87 loc) · 2.38 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import Promise from 'bluebird';
import _ from 'lodash';
import tracker from '../../../tracker';
import transformer from '../../../util/transformer';
const connection = {
id : 'mockedConnection',
};
const processResponse = function(obj) {
obj = obj || {};
if (obj.output) {
obj.result = obj.output.call(this, obj.result);
} else if (obj.method === 'first') {
obj.result = Array.isArray(obj.result) ? obj.result[0] : obj.result;
} else if (obj.method === 'pluck') {
obj.result = _.map(obj.result, obj.pluck);
}
return obj.result;
};
const _query = function _query(con, obj) {
obj.context = this;
obj.transacting = !! this.transacting;
return new Promise((resolve, reject) => tracker.queries.track(obj, resolve, reject));
};
export function defineConnection(conn) {
return {
'client.Runner.prototype.connection' : {
get() {
return conn;
},
set : _.noop,
},
};
}
export let spec = {
replace : [
{
client : {
_constructor : {
prototype : {
_stream(conn, sql, stream) {
return new Promise((resolver, rejecter) => {
stream.on('error', rejecter);
stream.on('end', resolver);
return this._query(conn, sql).then((obj) => {
return obj.response;
}).map((row) => {
stream.write(row);
}).catch((err) => {
stream.emit('error', err);
}).then(() => {
stream.end();
});
});
},
_query,
processResponse,
},
},
driverName : 'mocked',
acquireConnection : Promise.method(_.identity.bind(_, connection)),
acquireRawConnection : Promise.method(_.identity.bind(_, connection)),
destroyRawConnection : (con, cb) => cb(),
releaseConnection : _.noop,
processResponse,
Runner : {
prototype : {
ensureConnection() {
return Promise.resolve(this.connection || {});
},
},
},
},
},
],
define : defineConnection(connection),
};
export function makeClient(def) {
return {
mock(db) {
return transformer.transform(db, def);
},
unmock(db) {
return transformer.restore(db);
},
};
};
export default makeClient(spec);