This repository was archived by the owner on Jun 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathMethod.js
More file actions
86 lines (75 loc) · 2.82 KB
/
Method.js
File metadata and controls
86 lines (75 loc) · 2.82 KB
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
'use strict'
const SyntaxException = require('../../Exceptions/Syntax')
const ImplementationException = require('../../Exceptions/Implementation')
const Literally = require('../Helpers/Literally')
class Method {
/**
* @constructor
* @param {string} origin
* @param {string} methodName
* @param {function} buildQuery
*/
constructor(origin, methodName, buildQuery) {
/** @var {string} origin Contains the original method name (case-sensitive). */
this.origin = origin
/** @var {string} methodName Contains the method name to execute. */
this.methodName = methodName
/** @var {array} parameters Contains the parsed parameters to pass on execution. */
this.parameters = []
/** @var {array} executedCallbacks Contains all executed callbacks for that method. Helps finding "lost" groups. */
this.executedCallbacks = []
/** @var {function} buildQuery Reference to buildQuery since js DON'T support circular dependency well */
this.buildQuery = buildQuery
}
/**
* @param {Builder} builder
* @throws {SyntaxException}
* @return {Builder|mixed}
*/
callMethodOn(builder) {
const methodName = this.methodName
const parameters = this.parameters
try {
builder[methodName].apply(builder, parameters)
parameters.forEach((parameter, index) => {
if (
typeof parameter === 'function' &&
!this.executedCallbacks.includes(index)
) {
// Callback wasn't executed, but expected to. Assuming parentheses without method, so let's "and" it.
builder.group(parameter)
}
})
} catch (e) {
if (e instanceof ImplementationException) {
throw new SyntaxException(e.message)
} else {
throw new SyntaxException(`'${methodName}' does not allow the use of sub-queries.`)
}
}
}
/**
* Set and parse raw parameters for method.
*
* @param {array} params
* @throws {SyntaxException}
* @return {Method}
*/
setParameters(parameters) {
this.parameters = parameters.map((parameter, index) => {
if (parameter instanceof Literally) {
return parameter.toString()
} else if (Array.isArray(parameter)) {
// Assuming the user wanted to start a sub-query. This means, we'll create a callback for them.
return (builder) => {
this.executedCallbacks.push(index)
this.buildQuery(parameter, builder)
}
} else {
return parameter
}
})
return this
}
}
module.exports = Method