(ns auto-ap.effects (:require-macros [cljs.core.async.macros :refer [go]]) (:require [re-frame.core :as re-frame] [cljs-http.client :as http] [cljs-time.coerce :as c] [cljs-time.core :as time] [cljs-time.format :as format] [cljs.core.async :refer [date-times [x] (walk/postwalk (fn [node] (cond (and (string? node) (re-matches is-8601 node)) (format/parse (format/formatters :date-time) node) (instance? js/Date node) (time/to-default-time-zone (c/from-date node)) :else node)) x)) (re-frame/reg-fx :http (fn [{:keys [method uri on-success on-error body headers token]}] (go (let [headers (if token (assoc headers "Authorization" (str "Token " token)) headers) response (= (:status response) 400) (when on-error (->> response :body (dates->date-times) (conj on-error) (re-frame/dispatch))) (->> response :body (dates->date-times) (conj on-success) (re-frame/dispatch))))))) (re-frame/reg-fx :https (fn [{:keys [requests on-success on-failure]}] (go (let [results (->> (for [{:keys [method body headers uri token]} requests] (go (let [headers (if token (assoc headers "Authorization" (str "Token " token)) headers) response (= (:status response) 400) :error :success)))) (async/merge) (async/reduce conj []) (async/snake [s] (str/replace s #"-" "_")) (defn snake [x] (if (namespace x) (keyword (namespace x) (kebab->snake (name x))) (keyword (kebab->snake (name x))))) (defn ->graphql [m] (walk/postwalk (fn [node] (cond (keyword? node) (snake node) :else node)) m)) (defonce timeouts (atom {})) (re-frame/reg-fx :dispatch-debounce (fn [{:keys [event time key]}] (js/clearTimeout (@timeouts key)) (swap! timeouts assoc key (js/setTimeout (fn [] (re-frame/dispatch event) (swap! timeouts dissoc key)) time)))) (re-frame/reg-fx :graphql (fn [{:keys [query on-success on-error token variables query-obj]}] (go (let [headers (if token {"Authorization" (str "Token " token)} {}) method (if (= (get-in query-obj [:venia/operation :operation/type]) :mutation) :post :get) headers (if (= method :post) (assoc headers "Content-Type" "text/plain") headers ) query (or query (v/graphql-query (->graphql query-obj))) response (= (:status response) 400) (when on-error (->> response :body :errors (dates->date-times) (map #(assoc % :status (:status response))) (conj on-error) (re-frame/dispatch))) :else (->> response :body :data (dates->date-times) (conj on-success) (re-frame/dispatch)))))))