pattern.clj 1.58 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
(ns lacinia-datomic-pull.pattern)

(defn field-def->inner-type [fdef]
  (let [typ (get fdef :type)]
    (cond (keyword? typ) typ
          (nil? typ) (throw (ex-info "Could not get final type" {:fdef fdef}))
          :else (field-def->inner-type typ))))

(defn enum? [schema {:keys [field-definition] :as selection}]
  (and (:leaf? selection)
       (= :enum (:category (get schema (field-def->inner-type field-definition))))))

(defn list-selection? [schema selection]
  (= :list (->> selection :field-definition :type :kind)))

(defn selection->pull [schema type {:keys [leaf? field selections field-definition] :as selection}]
  (let [fqn (keyword (name type) (name field))
        list-default (when (list-selection? schema selection) [:default []])]
    (cond (enum? schema selection) {(into [fqn :as field] list-default) [:db/ident]}
          leaf? (into [fqn :as field] list-default)
          :else {(into [fqn :as field] list-default) (mapv #(selection->pull schema (field-def->inner-type field-definition) %) selections)})))

(defn context->pull-pattern
  [context]
  (let [schema (:com.walmartlabs.lacinia.constants/schema context)
        selections (:selections (:com.walmartlabs.lacinia/selection context))
        root-type (field-def->inner-type (->> context
                                              :com.walmartlabs.lacinia.constants/parsed-query
                                              :selections
                                              first
                                              :field-definition))]
    (mapv (partial selection->pull schema root-type) selections)))