Skip to content

Instantly share code, notes, and snippets.

@GEverding
Last active August 29, 2015 14:10
Show Gist options
  • Save GEverding/f09aec9dd16e10204ae3 to your computer and use it in GitHub Desktop.
Save GEverding/f09aec9dd16e10204ae3 to your computer and use it in GitHub Desktop.
Segment.io HTTP Api implement in Clojure
(ns server.analytics.segment
(:require [clj-http.client :as client]
[taoensso.timbre :as timbre]
[io.aviso.exception :as aviso]
[clojure.core.async :as async :refer (chan put! <! sliding-buffer go)]
[cheshire.core :refer (encode)]))
(timbre/refer-timbre)
(defonce ^:private endpoint "https://api.segment.io/v1")
(defonce ^:private pipe (chan (sliding-buffer 100)))
(defonce ^:private token (atom nil))
(defn- execute []
(debug "Setting up segment executer")
(go (loop [e (<! pipe)]
(debug "sending: " e)
(try
(let [url (str endpoint "/" (-> e :event name))
res (client/post url
{:content-type :json
:basic-auth @token
:body (-> e :body encode)
})]
(if (= (:status res) 200)
(debug "event sent")
(fatal "event failed: " (:body res)))
)
(catch Exception ex
(aviso/write-exception ex)))
(recur (<! pipe)))))
(defn initialize [t]
(info "initializing segment client")
(if token
(do
(reset! token t)
(execute)
true)
(do
(fatal "No Token Provided to Initialize client")
(throw (RuntimeException. "Missing Segment Key")))))
(defn identify [^String user-id traits & [{:keys [context timestamp integrations]}]]
(let [body {:userId user-id :traits traits }]
(go (put! pipe {:event :identify
:body body }))))
(defn group [^String user-id ^String group-id traits & [{:keys [context timestamp integrations]}]]
(let [body {:userId user-id
:groupId group-id
:traits traits
}]
(go (put! pipe {:event :group
:body body}))))
(defn track [^String user-id event props & [{:keys [context timestamp integrations]}]]
(let [body {:userId user-id
:event (name event)
:properties props}]
(go (put! pipe {:event :track
:body body}))))
(defn batch [events & [{:keys [context integrations]}]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment