├── .gitignore ├── LICENSE ├── README.md ├── changes.md ├── project.clj ├── src └── com │ └── gfredericks │ └── schema_bijections.clj └── test └── com └── gfredericks └── schema_bijections_test.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | .hgignore 11 | .hg/ 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # schema-bijections 2 | 3 | A first draft of a library for bijecting prismatic schemas. 4 | 5 | ## Obtention 6 | 7 | ``` 8 | [com.gfredericks/schema-bijections "0.1.3"] 9 | ``` 10 | 11 | ## Rationale 12 | 13 | I use [prismatic/schema](https://github.com/Prismatic/schema) a lot, 14 | and was excited when I learned about the coercers feature because I 15 | thought it would solve the problem of using boilerplate or messy 16 | shortcuts to convert data into fluent clojure representations (e.g., 17 | keyword keys, kebab-cased keys, joda types for timestamps, 18 | `java.util.UUID` instances for UUID's, etc.). 19 | 20 | A coercer is a function produced from a schema, which can convert 21 | objects that "almost" match the schema to objects that actually do 22 | match the schema. I had quickly figured out how to use coercers to 23 | solve all of the problems mentioned above, but I quickly noticed some 24 | drawbacks. 25 | 26 | My primary use case was for specifying a JSON HTTP API. I used schemas 27 | to describe the input and output data structures, in their 28 | clojure-fluent form. Among the drawbacks: 29 | 30 | - Coercers only helped for coercing the input, not the output. For 31 | output I had to convert key casing myself and hope that the default 32 | behavior of the json serializer did everything else correctly. 33 | - I didn't have a precise specification of the input or output schemas 34 | as they looked to the external world. I ended up writing some ad-hoc 35 | code to convert the prismatic schema to the json schema, which felt 36 | redundant with the coercer functionality 37 | - The server ended up being more lenient in what it would accept than 38 | I would like -- e.g., you could give it a json map that contained 39 | camel-cased keys or kebab-cased keys and it would accept either, 40 | which led to having production clients using one data format and 41 | tests using another format. I prefer knowing that both are the same. 42 | 43 | So this library is an attempt to solve the problem of transforming 44 | data between different formats in a more first-class way. 45 | 46 | The motivating use is to have a schema that describes the 47 | clojure-fluent data format for something, and then specify schema 48 | transformation functions to convert that schema to the variant 49 | format. The library composes the functions in much the same way 50 | that prismatic's coercers do, but the final result is: 51 | 52 | - a new schema for the variant format 53 | - two functions for converting objects between the two formats 54 | 55 | which I believe addresses the drawbacks listed above. 56 | 57 | ## Examples 58 | 59 | ``` clojure 60 | (require '[schema.core :as s] 61 | '[camel-snake-kebab.core :as csk] 62 | '[com.gfredericks.schema-bijections :as sb]) 63 | 64 | (def camelize-keys (sb/transform-keys csk/->camelCase)) 65 | 66 | (defn jsonify-schema 67 | [schema] 68 | (let [{:keys [left left->right right->left]} 69 | (sb/schema->bijection schema 70 | [sb/stringify-uuids 71 | sb/stringify-keys 72 | camelize-keys])] 73 | {:json-schema left 74 | :to-json right->left 75 | :from-json left->right})) 76 | 77 | (def User 78 | {:id s/Uuid 79 | :full-name s/Str 80 | :comments [{:id s/Uuid, :text s/Str}]}) 81 | 82 | (let [{:keys [json-schema from-json to-json]} 83 | (jsonify-schema User)] 84 | (def json->User from-json) 85 | (def User->json to-json) 86 | (def UserJson json-schema)) 87 | 88 | UserJson 89 | => {#schema.core.RequiredKey{:k "id"} 90 | #"^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$", 91 | 92 | #schema.core.RequiredKey{:k "fullName"} 93 | java.lang.String, 94 | 95 | #schema.core.RequiredKey{:k "comments"} 96 | [{#schema.core.RequiredKey{:k "id"} 97 | #"^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$", 98 | 99 | #schema.core.RequiredKey{:k "text"} 100 | java.lang.String}]} 101 | 102 | (def my-user {:id #uuid "0e90ab35-c550-40ff-ba8a-9e7da774c62c" 103 | :full-name "Tom Hanks" 104 | :comments [{:id #uuid "75d450b5-ebc7-43e5-a48c-b11f93e5f7dd" 105 | :text "Leave me be."}]}) 106 | 107 | (User->json my-user) 108 | => {"comments" 109 | [{"id" "75d450b5-ebc7-43e5-a48c-b11f93e5f7dd", 110 | "text" "Leave me be."}], 111 | "fullName" "Tom Hanks", 112 | "id" "0e90ab35-c550-40ff-ba8a-9e7da774c62c"} 113 | 114 | (= my-user (-> my-user User->json json->User)) 115 | => true 116 | ``` 117 | 118 | ## TODOs, caveats, etc. 119 | 120 | - Should the conversion functions always do full validation? Should 121 | that be configurable? 122 | - Integrating this with prismatic/fnhouse is currently a bit awkward. 123 | - Does the schema `1.0.0` change from `either` schemas to conditionals 124 | make it difficult to do anything generic with them? (i.e., without 125 | having to figure out how to "translate" each predicate) 126 | 127 | ## License 128 | 129 | Copyright © 2015 Gary Fredericks 130 | 131 | Distributed under the Eclipse Public License either version 1.0 or (at 132 | your option) any later version. 133 | -------------------------------------------------------------------------------- /changes.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## `0.1.0` 4 | 5 | Initial release, barely functional. 6 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject com.gfredericks/schema-bijections "0.1.4-SNAPSHOT" 2 | :description "A library for bijecting prismatic schemas." 3 | :url "https://github.com/gfredericks/schema-bijections" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure/clojure "1.7.0"] 7 | [prismatic/schema "1.0.3"] 8 | [prismatic/plumbing "0.5.2"]] 9 | :deploy-repositories [["releases" :clojars]] 10 | :profiles {:dev {:dependencies [[camel-snake-kebab "0.3.2"] 11 | [org.clojure/test.check "0.9.0"]]}}) 12 | -------------------------------------------------------------------------------- /src/com/gfredericks/schema_bijections.clj: -------------------------------------------------------------------------------- 1 | (ns com.gfredericks.schema-bijections 2 | (:require [plumbing.core :refer [for-map map-from-keys map-from-vals map-keys]] 3 | [schema.core :as s])) 4 | 5 | (def ^:private schema? #(satisfies? s/Schema %)) 6 | 7 | (defmacro ^:private throw-bijection-schema-error 8 | [data] 9 | `(throw (ex-info "Bijection schema error!" 10 | {:type ::bijection-schema-error 11 | :data ~data}))) 12 | 13 | (defn ^:private key-fmap 14 | [f k] 15 | ;; MONADS! 16 | (cond (keyword? k) (f k) 17 | (s/optional-key? k) (s/optional-key (f (:k k))) 18 | (s/required-key? k) (s/required-key (f (:k k))) 19 | :else (throw (ex-info "WTF?" {:k k})))) 20 | 21 | (declare walk) 22 | 23 | (defmulti walk* 24 | "Multimethod that walks a schema with a bijector. Should call walk 25 | instead of direct recursion. 26 | 27 | It should only be necessary to extend this multimethod to support 28 | new composite schemas." 29 | (fn [schema bijector] (type schema))) 30 | 31 | (defmethod walk* clojure.lang.IPersistentMap 32 | [schema bijector] 33 | ;; if this is ever a problem the solution is probably to create a 34 | ;; special walk* impl? I'm not sure why it would come up though. 35 | (assert (not (instance? clojure.lang.IRecord schema)) 36 | "Cannot walk records!") 37 | 38 | (letfn [(walk-map-with-no-key-schemas 39 | [schema] 40 | (let [key->bijection (for-map [[k v] schema] 41 | (s/explicit-schema-key k) 42 | (walk v bijector))] 43 | {:left (with-meta (map-from-keys (comp :left key->bijection s/explicit-schema-key) (keys schema)) 44 | (meta schema)) 45 | :left->right (fn [left-obj] 46 | (for-map [[k v] left-obj 47 | :let [{:keys [left->right]} (or (get key->bijection k) 48 | (throw-bijection-schema-error left-obj))]] 49 | k (left->right v))) 50 | :right->left (fn [right-obj] 51 | (for-map [[k v] right-obj 52 | :let [{:keys [right->left]} (or (get key->bijection k) 53 | (throw-bijection-schema-error right-obj))]] 54 | k (right->left v))) 55 | :right (with-meta (map-from-keys (comp :right key->bijection s/explicit-schema-key) (keys schema)) 56 | (meta schema))}))] 57 | (if-let [[key-schema & more-key-schemas] 58 | (seq (filter schema? (keys schema)))] 59 | (do 60 | (assert (empty? more-key-schemas)) 61 | (let [key-schema-bijection (walk key-schema bijector) 62 | val-schema-bijection (walk (get schema key-schema) bijector) 63 | 64 | {:keys [left left->right right->left right]} 65 | (walk-map-with-no-key-schemas (dissoc schema key-schema)) 66 | 67 | explicit-keys-on-right (map s/explicit-schema-key (keys right)) 68 | explicit-keys-on-left (map s/explicit-schema-key (keys left))] 69 | {:left 70 | (assoc left (:left key-schema-bijection) (:left val-schema-bijection)) 71 | 72 | :left->right 73 | (fn [left-obj] 74 | (-> left-obj 75 | (select-keys explicit-keys-on-left) 76 | (left->right) 77 | (merge (for-map [[k v] (apply dissoc left-obj explicit-keys-on-left)] 78 | ((:left->right key-schema-bijection) k) 79 | ((:left->right val-schema-bijection) v))))) 80 | 81 | :right->left 82 | (fn [right-obj] 83 | (-> right-obj 84 | (select-keys explicit-keys-on-right) 85 | (right->left) 86 | (merge (for-map [[k v] (apply dissoc right-obj explicit-keys-on-left)] 87 | ((:right->left key-schema-bijection) k) 88 | ((:right->left val-schema-bijection) v))))) 89 | 90 | :right 91 | (assoc right (:right key-schema-bijection) (:right val-schema-bijection))})) 92 | (walk-map-with-no-key-schemas schema)))) 93 | 94 | (defn ^:private one-schema? [x] (instance? schema.core.One x)) 95 | 96 | (defmethod walk* clojure.lang.IPersistentVector 97 | [schema bijector] 98 | (assert (not-any? #(and (one-schema? %) 99 | (:optional? %)) 100 | schema) 101 | ;; optional elements make the transformation functions near 102 | ;; impossible to implement because there's ambiguity about 103 | ;; which schema an element of the sequence is supposed to 104 | ;; match 105 | "Sequence schemas with optional elements are not supported!") 106 | (if (empty? schema) 107 | {:left [] :left->right identity :right->left identity :right []} 108 | (let [fmap (fn [f ob] 109 | (if (one-schema? ob) 110 | (let [{:keys [left left->right right->left right]} 111 | (f (:schema ob))] 112 | {:left (assoc ob :schema left) 113 | :left->right left->right 114 | :right->left right->left 115 | :right (assoc ob :schema right)}) 116 | (f ob))) 117 | walked (map #(fmap (fn [schema] (walk schema bijector)) %) schema) 118 | min-values (if (one-schema? (last schema)) 119 | (count schema) 120 | (dec (count schema))) 121 | max-values (if (one-schema? (last schema)) 122 | (count schema)) 123 | transform (fn [value schema transformers] 124 | (let [c (count value)] 125 | (if (< c min-values) 126 | (throw (ex-info "Not enough items in sequence!" 127 | {:schema schema 128 | :value value})) 129 | (if (and max-values (< max-values c)) 130 | (throw (ex-info "too many items in sequence!" 131 | {:schema schema 132 | :value value}))))) 133 | (mapv (fn [item transformer] 134 | (transformer item)) 135 | value 136 | (concat transformers 137 | (repeat (last transformers))))) 138 | left (mapv :left walked) 139 | right (mapv :right walked)] 140 | {:left left 141 | :left->right #(transform % left (map :left->right walked)) 142 | :right->left #(transform % right (map :right->left walked)) 143 | :right right}))) 144 | 145 | (defmethod walk* schema.core.Maybe 146 | [schema bijector] 147 | (let [{:keys [left left->right right->left right]} (walk (:schema schema) bijector)] 148 | {:left (s/maybe left) 149 | :left->right #(some-> % left->right) 150 | :right->left #(some-> % right->left) 151 | :right (s/maybe right)})) 152 | 153 | ;; This is the same as the :default impl, but we need it here to avoid 154 | ;; all the random schema defrecords getting sucked into the 155 | ;; IPersistentMap impl. 156 | (defmethod walk* clojure.lang.IRecord 157 | [schema bijector] 158 | {:left schema 159 | :left->right identity 160 | :right->left identity 161 | :right schema}) 162 | 163 | (defmethod walk* :default 164 | [schema bijector] 165 | {:left schema 166 | :left->right identity 167 | :right->left identity 168 | :right schema}) 169 | 170 | (prefer-method walk* clojure.lang.IRecord clojure.lang.IPersistentMap) 171 | 172 | (defn ^:private wrap-top-level-errors 173 | [{:keys [left left->right right->left right]}] 174 | {:left left 175 | :left->right (fn [left-obj] 176 | (try 177 | (left->right left-obj) 178 | (catch Throwable t 179 | (throw 180 | (if-let [err (s/check left left-obj)] 181 | (ex-info "Schema bijection error!" 182 | {:schema left 183 | :data left-obj 184 | :error err}) 185 | (ex-info "Unknown schema bijection error!" 186 | {:schema left 187 | :data left-obj} 188 | t)))))) 189 | :right->left (fn [right-obj] 190 | (try 191 | (right->left right-obj) 192 | (catch Throwable t 193 | (throw 194 | (if-let [err (s/check right right-obj)] 195 | (ex-info "Schema bijection error!" 196 | {:schema right 197 | :data right-obj 198 | :error err}) 199 | (ex-info "Unknown schema bijection error!" 200 | {:schema right 201 | :data right-obj} 202 | t)))))) 203 | :right right}) 204 | 205 | (defn walk 206 | [schema bijector] 207 | (bijector (walk* schema bijector))) 208 | 209 | (defn ^:private transformers->bijector 210 | [transformers] 211 | ;; I feel like I'm overcomplicating something. 212 | (if-let [[tx & txs] (seq transformers)] 213 | (let [bijector (transformers->bijector txs)] 214 | (fn [bijection] 215 | (let [{:keys [left left->right right->left right] :as bijection} 216 | (bijector bijection)] 217 | (if-let [{left' :left, left->right' :left->right, right->left' :right->left} 218 | (tx left)] 219 | {:left left' 220 | :left->right (comp left->right left->right') 221 | :right->left (comp right->left' right->left) 222 | :right right} 223 | bijection)))) 224 | identity)) 225 | 226 | (defn schema->bijection 227 | ;; I think I need some more intuitive terminology/concepts. 228 | "Given a schema and a sequence of transformers, returns a bijection. 229 | 230 | A transformer is a function from a schema to nil (when the schema is 231 | not the sort that the transformer intends to transform) or a map: 232 | :left the transformed schema 233 | :left->right a function that converts values from the transformed 234 | schema to the input schema 235 | :right->left a function that converts values from the input schema 236 | to the transformed schema 237 | 238 | A bijection is the same as the map returned from a transformer." 239 | [schema transformers] 240 | (try 241 | (wrap-top-level-errors 242 | (walk schema (transformers->bijector transformers))) 243 | (catch Throwable e 244 | (throw (ex-info "Exception while creating schema bijection!" 245 | {:schema schema 246 | :transformers transformers} 247 | e))))) 248 | 249 | ;; 250 | ;; The builtin transformers 251 | ;; 252 | 253 | (defn ^:private non-record-map? 254 | [m] 255 | (and (map? m) (not (record? m)))) 256 | 257 | (defn transform-keys 258 | "Given a function for transforming map keys, returns a transformer 259 | that transforms keys of map schemas. If a map schema has a 260 | key-schema, it will be ignored." 261 | [func] 262 | (fn [right] 263 | (when (non-record-map? right) 264 | (let [bare-keys (->> (keys right) 265 | (remove schema?) 266 | (map s/explicit-schema-key)) 267 | fk->k (for-map [k bare-keys] (func k) k) 268 | k->fk (for-map [k bare-keys] k (func k)) 269 | _ (when (not= (count fk->k) 270 | (count k->fk)) 271 | (throw (ex-info "Collision in transform-keys function!" 272 | {:schema right 273 | :func func 274 | :colliding-keys (->> bare-keys 275 | (group-by func) 276 | (vals) 277 | (filter #(< 1 (count %))) 278 | (first)) 279 | :type ::bad-input}))) 280 | 281 | extra-keys-schema (->> (keys right) (filter schema?) (first)) 282 | 283 | ;; I'm not sure if there's a decent use case for having 284 | ;; this work; at the moment if we don't have this check, 285 | ;; the generative test objects that key-stringifying the 286 | ;; map {"*" false, :* false} is ambiguous. 287 | _ (when extra-keys-schema 288 | (when-let [colliding (seq (filter #(nil? (s/check extra-keys-schema %)) (vals k->fk)))] 289 | (throw (ex-info "Potential collision in transform-keys function!" 290 | {:schema right 291 | :func func 292 | :schema-for-extra-keys extra-keys-schema 293 | :keys-colliding-with-schema-for-extra-keys colliding 294 | :type ::bad-input})))) 295 | 296 | left (map-keys (fn [k] 297 | (cond (keyword? k) 298 | (s/required-key (k->fk k)) 299 | 300 | (s/optional-key? k) 301 | (s/optional-key (k->fk (:k k))) 302 | 303 | (s/required-key? k) 304 | (s/required-key (k->fk (:k k))) 305 | 306 | (schema? k) 307 | k 308 | 309 | :else 310 | (throw (ex-info "Unknown key type" {:k k})))) 311 | right) 312 | 313 | left->right (fn [left-obj] 314 | (map-keys (fn [fk] 315 | (if-let [[_ k] (find fk->k fk)] 316 | k 317 | (if (and extra-keys-schema 318 | (nil? (s/check extra-keys-schema fk))) 319 | fk 320 | (throw (ex-info "Disallowed key!" 321 | {:schema left :key fk}))))) 322 | left-obj)) 323 | right->left (fn [right-obj] 324 | (map-keys (fn [k] 325 | (if-let [[_ fk] (find k->fk k)] 326 | fk 327 | (if (and extra-keys-schema 328 | (nil? (s/check extra-keys-schema k))) 329 | k 330 | (throw (ex-info "Disallowed key!" 331 | {:schema right :key k}))))) 332 | right-obj))] 333 | {:left (with-meta left (meta right)) 334 | :left->right left->right 335 | :right->left right->left})))) 336 | 337 | (defn stringify-uuids 338 | "A transformer that stringifys UUID schemas." 339 | [right] 340 | (when (= s/Uuid right) 341 | {:left #"^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$" 342 | :left->right #(java.util.UUID/fromString %) 343 | :right->left str})) 344 | 345 | (defn allow-extra-keys-on-left 346 | "Returns a transformer that will allow arbitrary extra map keys 347 | matching the given schema, and removes them when converting." 348 | [key-schema] 349 | (fn [right] 350 | (when (and (non-record-map? right) 351 | (not-any? #(satisfies? s/Schema %) (keys right))) 352 | (let [right-keys (map s/explicit-schema-key (keys right))] 353 | {:left (assoc right key-schema s/Any) 354 | :left->right (fn [left-obj] 355 | (select-keys left-obj right-keys)) 356 | :right->left identity})))) 357 | 358 | (def stringify-keys 359 | "A transformer that converts static keyword keys of maps into string 360 | keys." 361 | (transform-keys name)) 362 | 363 | (defn stringify-keyword-enums 364 | "A transformer that converts (s/enum :foo :bar :baz) to 365 | (s/enum \"foo\" \"bar\" \"baz\")." 366 | [schema] 367 | (when (and (instance? schema.core.EnumSchema schema) 368 | (every? keyword? (:vs schema))) 369 | (let [left->right (map-from-vals name (:vs schema)) 370 | right->left (map-from-keys name (:vs schema))] 371 | {:left (apply s/enum (keys left->right)) 372 | :left->right left->right 373 | :right->left right->left}))) 374 | -------------------------------------------------------------------------------- /test/com/gfredericks/schema_bijections_test.clj: -------------------------------------------------------------------------------- 1 | (ns com.gfredericks.schema-bijections-test 2 | (:require [camel-snake-kebab.core :as csk] 3 | [clojure.test :refer :all] 4 | [clojure.test.check.generators :as gen] 5 | [clojure.test.check.properties :as prop] 6 | [clojure.test.check.clojure-test :refer [defspec]] 7 | [com.gfredericks.schema-bijections :as sb :refer :all] 8 | [schema.core :as s] 9 | [schema.experimental.generators :as sgen])) 10 | 11 | (def camelize-keys (transform-keys csk/->camelCase)) 12 | 13 | (defn jsonify-schema 14 | [schema] 15 | (let [{:keys [left left->right right->left]} 16 | (schema->bijection schema 17 | [stringify-uuids 18 | stringify-keys 19 | camelize-keys])] 20 | {:json-schema left 21 | :to-json right->left 22 | :from-json left->right})) 23 | 24 | (deftest my-bijection 25 | (let [my-schema {:foo-bar s/Uuid 26 | (s/optional-key :thomas) s/Str 27 | :comments [{:text s/Str}]} 28 | 29 | {:keys [json-schema to-json from-json]} (jsonify-schema my-schema)] 30 | (are [my-obj json-obj] 31 | (and (s/validate my-schema my-obj) 32 | (s/validate json-schema json-obj) 33 | (= my-obj (from-json json-obj)) 34 | (= json-obj (to-json my-obj))) 35 | 36 | {:foo-bar #uuid "bcd82436-7962-4208-b460-853f5dd75d91" 37 | :comments []} 38 | {"fooBar" "bcd82436-7962-4208-b460-853f5dd75d91" 39 | "comments" []} 40 | 41 | {:foo-bar #uuid "bcd82436-7962-4208-b460-853f5dd75d91" 42 | :thomas "heyo" 43 | :comments [{:text "hiya"} {:text "it is"}]} 44 | {"fooBar" "bcd82436-7962-4208-b460-853f5dd75d91" 45 | "thomas" "heyo" 46 | "comments" [{"text" "hiya"} {"text" "it is"}]}))) 47 | 48 | (deftest collision-exception-test 49 | (is (thrown? clojure.lang.ExceptionInfo 50 | (jsonify-schema {:foo s/Int (s/required-key "foo") s/Uuid})))) 51 | 52 | (deftest top-level-errors-test 53 | (let [my-schema [{:name s/Str 54 | :comments [{:created-at s/Int 55 | :text s/Str}]}] 56 | {:keys [from-json to-json]} (jsonify-schema my-schema) 57 | 58 | from-ex (try (to-json [{:name "Joe" 59 | :comments [{:created-at 19 60 | :text "Somebody is wrong on the internet."} 61 | {:created-ats 42 62 | :text "Welp I don't know"}]}]) 63 | (is false "to-json didn't throw!") 64 | (catch Exception e e)) 65 | to-ex (try (from-json [{"name" "Joe" 66 | "comments" [{:created-at 19 67 | "text" "Somebody is wrong on the internet."} 68 | {"createdAt" 42 69 | "text" "Here goes nothing"}]}]) 70 | (is false "to-json didn't throw!") 71 | (catch Exception e e))] 72 | (is (re-find #"created-at missing-required-key" (pr-str from-ex))) 73 | (is (re-find #"\"createdAt\" missing-required-key" (pr-str to-ex))))) 74 | 75 | ;; 76 | ;; Custom bijections 77 | ;; 78 | 79 | (defn stringify-bigdecimals 80 | [right] 81 | (when (= java.math.BigDecimal right) 82 | {:left #"\d+(\.\d+)?M" 83 | :left->right (fn [s] 84 | (BigDecimal. (subs s 0 (dec (count s))))) 85 | :right->left pr-str})) 86 | 87 | 88 | (def my-schema 89 | {:id s/Uuid 90 | :the-amount java.math.BigDecimal}) 91 | 92 | (deftest custom-bijection-test 93 | (let [{:keys [left left->right right->left]} 94 | (schema->bijection my-schema [stringify-bigdecimals 95 | stringify-keys]) 96 | 97 | my-value {:id #uuid "bcd82436-7962-4208-b460-853f5dd75d91" 98 | :the-amount 42.9M}] 99 | (is (s/validate my-schema my-value)) 100 | (is (= (right->left my-value) 101 | {"id" #uuid "bcd82436-7962-4208-b460-853f5dd75d91" 102 | "the-amount" "42.9M"})) 103 | (is (= my-value (-> my-value right->left left->right))))) 104 | 105 | 106 | ;; 107 | ;; Properties 108 | ;; 109 | 110 | (def gen-leaf-schema 111 | (gen/one-of [(gen/elements [s/Bool 112 | s/Int 113 | Double 114 | Long 115 | s/Str 116 | s/Uuid]) 117 | (gen/let [kws (gen/set gen/keyword {:min-elements 1})] 118 | (apply s/enum kws))])) 119 | 120 | (def gen-schema 121 | ;; have to scale this since recursive-gen's sizing is still out of control 122 | (gen/scale #(min % 15) 123 | (gen/recursive-gen (fn [inner-gen] 124 | (gen/one-of [(gen/let [[one-schemas [rest-schema]] 125 | (gen/tuple (gen/vector inner-gen) 126 | (gen/vector inner-gen 0 1))] 127 | (cond-> (mapv #(s/one % "a-schema") one-schemas) 128 | rest-schema 129 | (conj rest-schema))) 130 | (gen/let [static-keys 131 | (gen/map gen/keyword inner-gen) 132 | 133 | dynamic-keys 134 | (gen/one-of 135 | [(gen/return nil) 136 | (gen/tuple inner-gen inner-gen)])] 137 | (cond-> static-keys 138 | dynamic-keys 139 | (conj dynamic-keys))) 140 | 141 | (gen/let [schema inner-gen] 142 | (s/maybe schema))])) 143 | gen-leaf-schema))) 144 | 145 | (def gen-transformers 146 | (gen/vector-distinct 147 | (gen/elements [stringify-uuids 148 | stringify-keys 149 | stringify-bigdecimals 150 | camelize-keys 151 | stringify-keyword-enums]))) 152 | 153 | (def roundtrip-scenario 154 | (gen/such-that 155 | (fn [{:keys [schema transformers]}] 156 | (try (schema->bijection schema transformers) 157 | (catch clojure.lang.ExceptionInfo e 158 | (when-not (or (= ::sb/bad-input (:type (ex-data e))) 159 | (= ::sb/bad-input (:type (ex-data (.getCause e))))) 160 | (throw e))))) 161 | (gen/let [[schema transformers] (gen/tuple gen-schema 162 | gen-transformers) 163 | x (gen/scale #(min % 15) (sgen/generator schema))] 164 | {:schema schema :transformers transformers :x x}))) 165 | 166 | (defspec roundtrip-spec 167 | (prop/for-all [{:keys [schema transformers x]} 168 | roundtrip-scenario] 169 | (let [{:keys [left left->right right->left]} 170 | (schema->bijection schema transformers)] 171 | (s/validate schema x) 172 | (s/validate left (right->left x)) 173 | (= x (-> x right->left left->right))))) 174 | 175 | (deftest extra-keys-test 176 | (let [schema {:foo-bar s/Int} 177 | {:keys [left left->right right->left]} 178 | (schema->bijection schema [(allow-extra-keys-on-left s/Keyword) 179 | camelize-keys])] 180 | (is (s/validate schema {:foo-bar 42})) 181 | (is (s/validate left {:fooBar -42 :some "other" :keys "here"})) 182 | (is (= {:foo-bar -42} (left->right {:fooBar -42 :some "other" :keys "here"}))) 183 | (is (= {:fooBar -42} (right->left {:foo-bar -42}))))) 184 | --------------------------------------------------------------------------------