Guest User

Untitled

a guest
Jun 21st, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. (ns gql-ns
  2. (:require
  3. [clojure.string :as str]))
  4.  
  5. (defn valid-gql-key?
  6. "Checks that a key has at most a single namespace separator."
  7. [k]
  8. (-> (name k)
  9. (str/replace #"^__" "")
  10. (str/replace #"__$" "")
  11. (->> (re-seq #"__")
  12. (count)
  13. (contains? #{0 1}))))
  14.  
  15. (defn ->clj [k type]
  16. (let [x (-> k
  17. name
  18. ;; Only double underscores in the middle of a name are considered
  19. ;; a namespace separator, so temporarily replace double underscores
  20. ;; at the start or end with a character that isn't valid graphql
  21. (str/replace #"^__" "@")
  22. (str/replace #"__$" "@")
  23. (str/replace "__" "/")
  24. (str/replace "_" "-")
  25. (str/replace "@" "__")
  26. (cond-> (= 'Boolean type) (str "?")))]
  27. (if-some [[_ ns n] (re-find #"^([^/]+)/([^/]+)$" x)]
  28. (keyword ns n)
  29. (keyword x))))
  30.  
  31. (defn ->gql [k type]
  32. (let [f #(-> % (str/replace "-" "_") (str/replace #"\?$" ""))
  33. n (name k)]
  34. (cond-> (if-some [ns (namespace k)]
  35. (str (f ns) "__" (f n))
  36. (f n))
  37. (= :enum type) (keyword))))
  38.  
  39. (defn valid-clj-key? [k type]
  40. (let [s (str (namespace k) (name k))]
  41. (or (not= type 'Boolean)
  42. (and (str/ends-with? s "?")
  43. (= 1 (count (re-seq #"\?" s)))))))
  44.  
  45. (comment
  46.  
  47. (->clj (->gql :foo/bar? 'Boole) 'Boolean)
  48.  
  49. (->clj "foo__" 'asd)
  50.  
  51. (->clj "__foo__" 'asd)
  52.  
  53. (->clj "foo_bar__baz_quux" 'Foo)
  54.  
  55. (->clj "foo__bar" 'Boolean)
  56.  
  57. (->clj "person__name" 'String)
  58.  
  59. (->clj "person__politically_exposed" 'Boolean)
  60.  
  61. (->gql :person/name 'String)
  62.  
  63. (valid-gql-key? "foo__bar__baz")
  64.  
  65.  
  66. )
Add Comment
Please, Sign In to add comment