Added .aggs method to fluent API and improved query merger

This commit is contained in:
delvedor
2020-09-03 17:37:31 +02:00
parent c82ac4f5aa
commit 7f0e56b444
3 changed files with 17 additions and 14 deletions

View File

@ -24,11 +24,7 @@
import * as t from './types'
interface anyObject {
[key: string]: any
}
type aggsOptions = anyObject | string
type aggsOptions = Record<string, any> | string
function _A (...aggregations: any[]): any {
return {
@ -106,7 +102,7 @@ interface Aggregations {
}
const aggregations = {
get: function (target: unknown, name: string) {
get (target: unknown, name: string) {
return {
// add aggregations to a parent aggregation
aggs (...aggregations: any[]): t.Aggregation {

View File

@ -25,12 +25,13 @@
/* eslint lines-between-class-members: 0 */
import Q from './query'
import A from './aggregation'
import * as t from './types'
const kState = Symbol('dsl-state')
type nestedQFn = (f: Fluent) => Fluent
const kState = Symbol('dsl-query-state')
type nestedQFn = (f: FluentQ) => FluentQ
class Fluent {
class FluentQ {
[kState]: Record<string, any>[]
constructor () {
this[kState] = []
@ -257,6 +258,11 @@ class Fluent {
this[kState].push(Q.size(s))
return this
}
aggs (...aggregations: Record<string, any>[]): this {
this[kState].push(A(...aggregations))
return this
}
}
export default Fluent
export default FluentQ

View File

@ -27,6 +27,7 @@ import deepMerge from 'deepmerge'
import * as t from './types'
function Q (...blocks: t.AnyQuery[]): Record<string, any> {
blocks = blocks.flat()
const topLevelKeys = [
'aggs',
'collapse',
@ -51,10 +52,10 @@ function Q (...blocks: t.AnyQuery[]): Record<string, any> {
'version'
]
const queries = blocks.flat().filter(block => {
return !topLevelKeys.includes(Object.keys(block)[0])
})
const body: Record<string, any> = queries.length > 0 ? Q.bool(...queries) : {}
const queries = blocks.filter(block => !topLevelKeys.includes(Object.keys(block)[0]))
const body: Record<string, any> = queries.length === 1 && !isClause(queries[0]) && !isBool(queries[0])
? { query: queries[0] }
: queries.length > 0 ? Q.bool(...queries) : {}
for (const block of blocks) {
const key = Object.keys(block)[0]
if (topLevelKeys.includes(key)) {