Skip to content

Commit

Permalink
feat(promql): add promql builder
Browse files Browse the repository at this point in the history
  • Loading branch information
alili committed Aug 30, 2023
1 parent fc8d49d commit 3de76b3
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 1 deletion.
84 changes: 83 additions & 1 deletion src/promql.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
import { formatResult } from './utils'
import axios, { AxiosRequestConfig } from 'axios'
import { PromQLArgs, PromQLResultState } from './type/promql'
import { PromQLArgs, PromQLParams, PromQLResultState } from './type/promql'
import { FormatResultState, QueryResData } from './type/common'

const dayjs = require('dayjs')
class PromQL {
url: string
args: PromQLArgs
params: PromQLParams

constructor(db: string) {
this.url = '/v1/promql'
this.params = {
metrics: '',
selectors: [],
range: '',
field: '',
functions: [],
}
this.args = {
query: '',
start: dayjs().subtract(5, 'm').unix(),
Expand Down Expand Up @@ -48,7 +56,81 @@ class PromQL {
return this
}

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

selectors = (selectors: string | Object) => {
this.params.selectors =
typeof selectors === 'string'
? selectors.split(',')
: Object.entries(selectors).map(([key, value]) => {
let [_, k, operation] = key.match(/^(.*?)([!~=]*)$/)
switch (operation) {
case '!':
case '!=':
operation = '!='
break
case '~':
case '=~':
operation = '=~'
break
case '!~':
operation = '!~'
break
case '=':
default:
operation = '='
break
}
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
}

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 (this.params.range) {
query += `[${this.params.range}]`
}

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

let res: QueryResData = await axios.post(this.url, {}, {
params: this.args,
} as AxiosRequestConfig)
Expand Down
7 changes: 7 additions & 0 deletions src/type/promql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,10 @@ export interface PromQLArgs {
step: string
db: string
}
export interface PromQLParams {
metrics: string
selectors: string[]
range: string
field: string
functions: string[]
}

0 comments on commit 3de76b3

Please sign in to comment.