cognitect-labs / vase

Data driven microservices
Eclipse Public License 1.0
374 stars 40 forks source link

Float coercion #69

Open deg opened 7 years ago

deg commented 7 years ago

Javascript does not have distinct integer and float types. Therefore, 2.0 and 2 are equal.

When 2.0 is sent to the server (at least in JSON; probably also in Transit, though I've not tested), the server sees it as 2.

If my Vase schema has an attribute of type :float, a run-time error will be generated if the client passes a number that happens to be an integer (even if it was created by code that thinks it is dealing with floats).

This risk of surprise could be avoided if Vase would accept and coerce integers into float fields.

For now, I can work around this with a trivial interceptor, but it would be better if automated. The following ten lines are a much too verbose way to ensure that one float field works safely!

(def float-conversion
  (i/interceptor
   {:name ::float-conversion
    :enter (fn [context]
             (let [payloads (get-in context [:request :json-params :payload])
                   payloads (map (fn [m] (if (:purchase/price m)
                                           (update m :purchase/price float)
                                           m))
                                 payloads)]
               (assoc-in context [:request :json-params :payload] payloads)))}))
deg commented 7 years ago

Note that there is also an outstanding feature request to include this in Datomic: https://receptive.io/app/#/case/17714.