Skip to content

Instantly share code, notes, and snippets.

@madstap
Created June 19, 2018 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madstap/757750e6ee76d29fb222dcd56f769a3c to your computer and use it in GitHub Desktop.
Save madstap/757750e6ee76d29fb222dcd56f769a3c to your computer and use it in GitHub Desktop.
namespaces for graphql
(ns gql-ns
(:require
[clojure.string :as str]))
(defn valid-gql-key?
"Checks that a key has at most a single namespace separator."
[k]
(-> (name k)
(str/replace #"^__" "")
(str/replace #"__$" "")
(->> (re-seq #"__")
(count)
(contains? #{0 1}))))
(defn ->clj [k type]
(let [x (-> k
name
;; Only double underscores in the middle of a name are considered
;; a namespace separator, so temporarily replace double underscores
;; at the start or end with a character that isn't valid graphql
(str/replace #"^__" "@")
(str/replace #"__$" "@")
(str/replace "__" "/")
(str/replace "_" "-")
(str/replace "@" "__")
(cond-> (= 'Boolean type) (str "?")))]
(if-some [[_ ns n] (re-find #"^([^/]+)/([^/]+)$" x)]
(keyword ns n)
(keyword x))))
(defn ->gql [k type]
(let [f #(-> % (str/replace "-" "_") (str/replace #"\?$" ""))
n (name k)]
(cond-> (if-some [ns (namespace k)]
(str (f ns) "__" (f n))
(f n))
(= :enum type) (keyword))))
(defn valid-clj-key? [k type]
(let [s (str (namespace k) (name k))]
(or (not= type 'Boolean)
(and (str/ends-with? s "?")
(= 1 (count (re-seq #"\?" s)))))))
(comment
(->clj (->gql :foo/bar? 'Boole) 'Boolean)
(->clj "foo__" 'asd)
(->clj "__foo__" 'asd)
(->clj "foo_bar__baz_quux" 'Foo)
(->clj "foo__bar" 'Boolean)
(->clj "person__name" 'String)
(->clj "person__politically_exposed" 'Boolean)
(->gql :person/name 'String)
(valid-gql-key? "foo__bar__baz")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment