Skip to content

Commit

Permalink
Merge pull request #5 from vinted/feature/add_now_function
Browse files Browse the repository at this point in the history
graphql-exporter: add NOW function
  • Loading branch information
Seitanas authored Sep 6, 2024
2 parents 0efcffb + 5260b24 commit f7a0113
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ Exporter is designed to build and display metrics based on GraphQL query results
}
```

Query supports dynamic `datetime` field. It can be specified as template variable.
For example when specified `{{NOW ""-1h"}}` query will generate `datetime` that existed one hour ago.

Metrics results in:

```
Expand Down
2 changes: 1 addition & 1 deletion config_example.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"CacheExpire": 0,
"queries":[
{
"query": "query {device_list {name serial custom_fields}}",
"query": "query {device_list {name serial custom_fields}} {{NOW "-1h"}}",
"metrics": [
{
"description": "Deprecation date",
Expand Down
28 changes: 27 additions & 1 deletion pkg/config/config.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package config

import (
"bytes"
"encoding/json"
"fmt"
"log"
"os"
"text/template"
"time"
)

type Cfg struct {
Expand All @@ -30,6 +34,13 @@ var (
ConfigPath string
)

var funcMap = template.FuncMap{
"NOW": func(t string) (string, error) {
d, err := time.ParseDuration(t)
return time.Now().UTC().Add(d).Format(time.RFC3339), err
},
}

func Init(configPath string) error {
ConfigPath = configPath
content := []byte(`{}`)
Expand All @@ -43,7 +54,22 @@ func Init(configPath string) error {
if len(content) == 0 {
content = []byte(`{}`)
}
err = json.Unmarshal(content, &Config)

if err != nil {
return fmt.Errorf("%s", err)
}
tpl, err := template.New("query").Funcs(funcMap).Parse(string(content))
if err != nil {
return fmt.Errorf("%s", err)
}

var templateBuffer bytes.Buffer
err = tpl.Execute(&templateBuffer, nil)
if err != nil {
return fmt.Errorf("Template error %s", err)
}

err = json.Unmarshal(templateBuffer.Bytes(), &Config)
if err != nil {
return err
}
Expand Down

0 comments on commit f7a0113

Please sign in to comment.