Skip to content

Commit

Permalink
[type] add regex pattern support for strings
Browse files Browse the repository at this point in the history
  • Loading branch information
lispyclouds committed Sep 29, 2024
1 parent 92206a9 commit a568b6a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
21 changes: 17 additions & 4 deletions src/navi/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -85,16 +85,27 @@
.getSchema
schema->spec))))

(defn matches-regex?
[exp s]
(-> exp
(re-pattern)
(re-matches s)
(some?)))

(defmulti spec
(fn [^Schema schema]
(or (first (.getTypes schema)) "null")))

(defmethod spec
"string"
[^Schema schema]
(if (= "uuid" (.getFormat schema))
uuid?
string?))
(let [content-fn (if (= "uuid" (.getFormat schema))
uuid?
string?)
pattern (.getPattern schema)]
(if pattern
[:and content-fn [:fn #(matches-regex? pattern %)]]
content-fn)))

(defmethod spec
"integer"
Expand Down Expand Up @@ -283,4 +294,6 @@
(-> "api.yaml"
slurp
(routes-from handlers)
pp/pprint))
pp/pprint)

(matches-regex? "^(\\d+)([KMGTPE]i{0,1})$" "1024Mi"))
12 changes: 10 additions & 2 deletions test/navi/core_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,20 @@
(core/schema->spec (doto (Schema.)
(.addType "string")
(.setFormat "uuid"))))))

(testing "jsonschemas with multiple types"
(let [strint (-> (JsonSchema.)
(.types #{"string" "integer"}))]
(is (#{[:or string? int?] [:or int? string?]}
(core/schema->spec strint))))))
(core/schema->spec strint)))))
(testing "regex string"
(let [[kw1 fn1 [kw2 fn2]] (core/schema->spec (doto (Schema.)
(.addType "string")
(.setPattern "^(\\d+)([KMGTPE]i{0,1})$")))]
(is (= :and kw1))
(is (= string? fn1))
(is (= :fn kw2))
(is (fn2 "1024Ki"))
(is (not (fn2 "1024Kib"))))))

(deftest responses-to-malli-spec
(testing "empty response"
Expand Down

0 comments on commit a568b6a

Please sign in to comment.