59 lines
1.2 KiB
Go
59 lines
1.2 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
nocodelytics_schemas "github.com/nocodelytics/schemas"
|
|
"github.com/nocodelytics/tracker-api/internal"
|
|
"github.com/xeipuuv/gojsonschema"
|
|
)
|
|
|
|
var schema = nocodelytics_schemas.BuildEventsQueueInputSchemas()
|
|
|
|
func TrackEvent(c *gin.Context) {
|
|
nc := internal.NewNatsConnection()
|
|
id, _ := uuid.NewRandom()
|
|
ipAddress := c.ClientIP()
|
|
userAgent := c.Request.Header.Get("User-Agent")
|
|
createdAt := time.Now().Format(time.RFC3339)
|
|
|
|
data := gin.H{
|
|
"id": id,
|
|
"ip": ipAddress,
|
|
"userAgent": userAgent,
|
|
"createdAt": createdAt,
|
|
}
|
|
|
|
for k, v := range c.Request.URL.Query() {
|
|
data[k] = v[0]
|
|
}
|
|
|
|
documentLoader := gojsonschema.NewGoLoader(data)
|
|
result, err := schema.Validate(documentLoader)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
var errors []string
|
|
for _, val := range result.Errors() {
|
|
errors = append(errors, val.String())
|
|
}
|
|
if !result.Valid() {
|
|
c.JSON(http.StatusBadRequest, gin.H{"errors": errors})
|
|
return
|
|
}
|
|
|
|
jsonData, _ := json.Marshal(data)
|
|
nc.Publish("events", []byte(jsonData))
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"ok": 1,
|
|
"id": id,
|
|
})
|
|
|
|
}
|