Skip to content

Commit a568b6a

Browse files
committed
[type] add regex pattern support for strings
1 parent 92206a9 commit a568b6a

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

src/navi/core.clj

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -85,16 +85,27 @@
8585
.getSchema
8686
schema->spec))))
8787

88+
(defn matches-regex?
89+
[exp s]
90+
(-> exp
91+
(re-pattern)
92+
(re-matches s)
93+
(some?)))
94+
8895
(defmulti spec
8996
(fn [^Schema schema]
9097
(or (first (.getTypes schema)) "null")))
9198

9299
(defmethod spec
93100
"string"
94101
[^Schema schema]
95-
(if (= "uuid" (.getFormat schema))
96-
uuid?
97-
string?))
102+
(let [content-fn (if (= "uuid" (.getFormat schema))
103+
uuid?
104+
string?)
105+
pattern (.getPattern schema)]
106+
(if pattern
107+
[:and content-fn [:fn #(matches-regex? pattern %)]]
108+
content-fn)))
98109

99110
(defmethod spec
100111
"integer"
@@ -283,4 +294,6 @@
283294
(-> "api.yaml"
284295
slurp
285296
(routes-from handlers)
286-
pp/pprint))
297+
pp/pprint)
298+
299+
(matches-regex? "^(\\d+)([KMGTPE]i{0,1})$" "1024Mi"))

test/navi/core_test.clj

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,12 +121,20 @@
121121
(core/schema->spec (doto (Schema.)
122122
(.addType "string")
123123
(.setFormat "uuid"))))))
124-
125124
(testing "jsonschemas with multiple types"
126125
(let [strint (-> (JsonSchema.)
127126
(.types #{"string" "integer"}))]
128127
(is (#{[:or string? int?] [:or int? string?]}
129-
(core/schema->spec strint))))))
128+
(core/schema->spec strint)))))
129+
(testing "regex string"
130+
(let [[kw1 fn1 [kw2 fn2]] (core/schema->spec (doto (Schema.)
131+
(.addType "string")
132+
(.setPattern "^(\\d+)([KMGTPE]i{0,1})$")))]
133+
(is (= :and kw1))
134+
(is (= string? fn1))
135+
(is (= :fn kw2))
136+
(is (fn2 "1024Ki"))
137+
(is (not (fn2 "1024Kib"))))))
130138

131139
(deftest responses-to-malli-spec
132140
(testing "empty response"

0 commit comments

Comments
 (0)