-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
98 lines (79 loc) · 2.76 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
module.exports = Model => {
class FinderQueryBuilder extends Model.QueryBuilder {
get finder() {
let queryString = null
// The proxy adds a getter for a query string.
// Upon calling the proxy function, the string is parsed into `where` statements
const proxy = new Proxy((...args) => {
let whereTerm = 'where'
let offsetLetter = ''
let argCount = 0
const schema = this.modelClass().getJsonSchema()
const hasSchema = schema && schema.properties
// For queryStrings that end in 'OrFail', fail if no models are found ex. firstNameOrFail
if(queryString.slice(-6) === 'OrFail') {
this._failIfNotFound()
queryString = queryString.slice(0, -6)
}
// Test for beginning 'or' statement ex. orFirstname
if(/^or[A-Z]/.test(queryString)) {
queryString = queryString[2].toLowerCase() + queryString.slice(3)
whereTerm = 'orWhere'
}
// Split on 'And' or 'Or', using capture groups to keep them in the result set
for(const term of queryString.split(/(?:(Or|And)([A-Z]))/)) {
if(term.length === 1) {
// Corrects for issue splitting on capture groups
offsetLetter = term
continue
} else if((term === 'And') || (term === 'Or')) {
whereTerm = term === 'And' ? 'where' : 'orWhere'
continue
}
// Convert query string from camelCase to snake_case
const cameled = (offsetLetter.toLowerCase() + term)
const searchField = cameled.replace(/(.)([A-Z])/, '$1_$2').toLowerCase()
// If a jsonSchema is defined on the model, use it to validate that the queried fields exist
if(hasSchema) {
if((schema.properties[searchField] === void 0) && (schema.properties[cameled] === void 0)) {
throw new Error(
`Querying invalid field: ${searchField}. Please fix the query or update the jsonSchema.`
)
}
}
// Add the where() query
this[whereTerm](searchField, args[argCount ++])
}
// Return the QueryBuilder to support further query chaining
return this
}, {
get: (object, prop) => {
queryString = prop
// Return the proxy so it can then be called
return proxy
}
})
// Return the proxy to allow accces to the getter
return proxy
}
// Use throwIfNotFound on Objection >= 0.8.1. Else mimic its basic functionality.
_failIfNotFound() {
if(typeof this.throwIfNotFound === 'function') {
return this.throwIfNotFound()
}
return this.runAfter(result => {
if(Array.isArray(result) && result.length === 0) {
throw new Error('No models found')
} else if([ null, undefined, 0 ].includes(result)) {
throw new Error('No models found')
}
return result
})
}
}
return class extends Model {
static get QueryBuilder() {
return FinderQueryBuilder
}
}
}