From b82291d7eb78e6842f4c87505dba36f9c9bfe7ed Mon Sep 17 00:00:00 2001 From: Zachary Kim Date: Sun, 1 Mar 2015 00:30:23 -0800 Subject: [PATCH] Initial validation code --- src/clj/nsfw/validate.clj | 21 +++++++++++++++++++++ test/clj/nsfw/validate_test.clj | 24 ++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 src/clj/nsfw/validate.clj create mode 100644 test/clj/nsfw/validate_test.clj diff --git a/src/clj/nsfw/validate.clj b/src/clj/nsfw/validate.clj new file mode 100644 index 0000000..d312c09 --- /dev/null +++ b/src/clj/nsfw/validate.clj @@ -0,0 +1,21 @@ +(ns nsfw.validate + (:refer-clojure :exclude [key])) + +(defn run [payload vs] + (->> vs + (map (fn [f] + (f payload))) + (apply merge-with concat))) + +(defn key [k & opts] + (let [msg (last opts) + fns (butlast opts)] + (fn [pl] + (let [pass? (->> fns + (map (fn [f] + (f (get pl k)))) + (reduce #(and %1 %2)))] + (if-not pass? + {k [msg]}))))) + +(def not-empty? #(not (empty? %))) diff --git a/test/clj/nsfw/validate_test.clj b/test/clj/nsfw/validate_test.clj new file mode 100644 index 0000000..842a614 --- /dev/null +++ b/test/clj/nsfw/validate_test.clj @@ -0,0 +1,24 @@ +(ns nsfw.validate-test + (:require [clojure.test :refer :all] + [nsfw.validate :as v])) + + +(deftest test-key + (is ((v/key :foo v/not-empty? "error") {}))) + +(deftest test-run + (is (v/run + {:asdf "bar"} + [(fn [pl] + (if (empty? (:foo pl)) + {:foo [":foo can't be empty"]})) + (fn [pl] + (when (empty? (:bar pl)) + {:bar [":bar can't be empty"]})) + (fn [pl] + (if (empty? (:foo pl)) + {:foo [":foo some other thing"]})) + (fn [pl] + (if (empty? (:foo pl)) + {:message "Here's a general message"})) + (v/key :foo v/not-empty? "Key message not empty")])))