1 | const { isEmpty, map, clone, each } = require('lodash');
|
2 |
|
3 | module.exports = function(Target) {
|
4 | Target.prototype.toQuery = function(tz) {
|
5 | let data = this.toSQL(this._method, tz);
|
6 | if (!Array.isArray(data)) data = [data];
|
7 | return map(data, (statement) => {
|
8 | return this.client._formatQuery(statement.sql, statement.bindings, tz);
|
9 | }).join(';\n');
|
10 | };
|
11 |
|
12 |
|
13 | Target.prototype.then = function(/* onFulfilled, onRejected */) {
|
14 | let result = this.client.runner(this).run();
|
15 |
|
16 | if (this.client.config.asyncStackTraces) {
|
17 | result = result.catch((err) => {
|
18 | err.originalStack = err.stack;
|
19 | const firstLine = err.stack.split('\n')[0];
|
20 | this._asyncStack.unshift(firstLine);
|
21 |
|
22 | err.stack = this._asyncStack.join('\n');
|
23 | throw err;
|
24 | });
|
25 | }
|
26 |
|
27 | return result.then.apply(result, arguments);
|
28 | };
|
29 |
|
30 |
|
31 |
|
32 | Target.prototype.options = function(opts) {
|
33 | this._options = this._options || [];
|
34 | this._options.push(clone(opts) || {});
|
35 | return this;
|
36 | };
|
37 |
|
38 |
|
39 | Target.prototype.connection = function(connection) {
|
40 | this._connection = connection;
|
41 | return this;
|
42 | };
|
43 |
|
44 |
|
45 | Target.prototype.debug = function(enabled) {
|
46 | this._debug = arguments.length ? enabled : true;
|
47 | return this;
|
48 | };
|
49 |
|
50 |
|
51 | Target.prototype.transacting = function(t) {
|
52 | if (t && t.client) {
|
53 | if (!t.client.transacting) {
|
54 | t.client.logger.warn(`Invalid transaction value: ${t.client}`);
|
55 | } else {
|
56 | this.client = t.client;
|
57 | }
|
58 | }
|
59 | if (isEmpty(t)) {
|
60 | this.client.logger.error(
|
61 | 'Invalid value on transacting call, potential bug'
|
62 | );
|
63 | throw Error(
|
64 | 'Invalid transacting value (null, undefined or empty object)'
|
65 | );
|
66 | }
|
67 | return this;
|
68 | };
|
69 |
|
70 |
|
71 | Target.prototype.stream = function(options) {
|
72 | return this.client.runner(this).stream(options);
|
73 | };
|
74 |
|
75 |
|
76 | Target.prototype.pipe = function(writable, options) {
|
77 | return this.client.runner(this).pipe(
|
78 | writable,
|
79 | options
|
80 | );
|
81 | };
|
82 |
|
83 |
|
84 |
|
85 | each(
|
86 | [
|
87 | 'bind',
|
88 | 'catch',
|
89 | 'finally',
|
90 | 'asCallback',
|
91 | 'spread',
|
92 | 'map',
|
93 | 'reduce',
|
94 | 'thenReturn',
|
95 | 'return',
|
96 | 'yield',
|
97 | 'ensure',
|
98 | 'reflect',
|
99 | 'get',
|
100 | 'mapSeries',
|
101 | 'delay',
|
102 | ],
|
103 | function(method) {
|
104 | Target.prototype[method] = function() {
|
105 | const promise = this.then();
|
106 | return promise[method].apply(promise, arguments);
|
107 | };
|
108 | }
|
109 | );
|
110 | };
|