Skip to content

Commit

Permalink
fix(promql): add builder function
Browse files Browse the repository at this point in the history
  • Loading branch information
alili committed Aug 30, 2023
1 parent 3de76b3 commit a550f11
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 46 deletions.
71 changes: 27 additions & 44 deletions src/promql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,15 @@ class PromQL {
return this
}

metrics = (metrics: string) => {
this.params.metrics = metrics
return this
}
//promQL builder
builder = (options: PromQLParams) => {
let { metrics, selectors, range, field, functions } = options
if (!metrics) {
return Promise.reject('wrong promQL query')
}

selectors = (selectors: string | Object) => {
this.params.selectors =
const functionsArr = Array.isArray(functions) ? functions : [functions]
const selectorsArr =
typeof selectors === 'string'
? selectors.split(',')
: Object.entries(selectors).map(([key, value]) => {
Expand All @@ -74,6 +76,7 @@ class PromQL {
break
case '~':
case '=~':
case '~=':
operation = '=~'
break
case '!~':
Expand All @@ -86,51 +89,31 @@ class PromQL {
}
return `${k}${operation}'${value}'`
})
return this
}
field = (field: string) => {
this.params.field = field
return this
}

range = (range: string) => {
this.params.range = range
return this
}

functions = (functions: string | string[]) => {
this.params.functions = Array.isArray(functions) ? functions : [functions]
return this
}
let query = metrics

run = async (): Promise<PromQLResultState> => {
if (!this.args.query) {
if (!this.params.metrics) {
return Promise.reject('wrong promQL query')
}

let query = this.params.metrics

if (this.params.selectors.length) {
if (this.params.field) {
this.params.selectors.push(`__field__='${this.params.field}'`)
}
query += `{${this.params.selectors.join()}}`
if (selectorsArr.length) {
if (field) {
selectorsArr.push(`__field__='${field}'`)
}
query += `{${selectorsArr.join()}}`
}

if (this.params.range) {
query += `[${this.params.range}]`
}
if (range) {
query += `[${range}]`
}

if (this.params.functions.length) {
this.params.functions.forEach((fn) => {
query = `${fn}(${query})`
})
}
console.log(`query:`, query)
this.args.query = query
if (functionsArr.length) {
functionsArr.forEach((fn) => {
query = `${fn}(${query})`
})
}

this.args.query = query
return this
}

run = async (): Promise<PromQLResultState> => {
let res: QueryResData = await axios.post(this.url, {}, {
params: this.args,
} as AxiosRequestConfig)
Expand Down
4 changes: 2 additions & 2 deletions src/type/promql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ export interface PromQLArgs {
}
export interface PromQLParams {
metrics: string
selectors: string[]
selectors: string | Object
range: string
field: string
functions: string[]
functions: string | string[]
}

0 comments on commit a550f11

Please sign in to comment.