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