Created
June 19, 2018 21:41
-
-
Save madstap/757750e6ee76d29fb222dcd56f769a3c to your computer and use it in GitHub Desktop.
namespaces for graphql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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