Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (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")
- )
Add Comment
Please, Sign In to add comment