Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Using Java classes as schemas #1007

Open
NoahTheDuke opened this issue Feb 2, 2024 · 4 comments
Open

Feature: Using Java classes as schemas #1007

NoahTheDuke opened this issue Feb 2, 2024 · 4 comments
Labels
enhancement New feature or request

Comments

@NoahTheDuke
Copy link
Contributor

Occasionally, it is necessary to drop down to Java interop. When that happens, I don't want to lose the ease and simplicity of Malli's validation, and I don't want to have to write my own custom :fn schema each time merely to call (instance? SomeClass value).

It would be helpful to have support for recognizing Java classes, effectively wrapping instance? for general use. I looked at the malli.core code and I'm not entirely sure how to accomplish this or I'd offer to do it.

Thanks so much

@ikitommi ikitommi added the enhancement New feature or request label Feb 4, 2024
@ikitommi
Copy link
Member

ikitommi commented Feb 4, 2024

Something like this:

(defn -class-schema [c]
  (m/-simple-schema
   {:type c
    :pred #(instance? c %)
    :type-properties {:error/message (str "not an instance of class " c)}}))

(defn class-registry
  ([] (class-registry nil))
  ([_options]
   (reify
     mr/Registry
     (-schema [_ type] (when (class? type) (-class-schema type)))
     (-schemas [_]))))

(def registry
  (mr/composite-registry
   m/default-registry
   (class-registry)))

(def Schema
  (m/schema
   [:map
    [:str String]
    [:long Long]]
   {:registry registry}))

(-> (m/explain
     Schema
     {:str "kikka"
      :long "123"})
    (me/humanize))
; => {:long ["not an instance of class class java.lang.Long"]}

You can use that if you need this now. Let's add this to malli as optional part, need to define transformers, json-schema mappings etc for them to be complete.

@ikitommi
Copy link
Member

ikitommi commented Feb 4, 2024

original issue #75

@jasonjckn
Copy link
Contributor

jasonjckn commented Sep 4, 2024

Related Q: is there interest in a new [:satisfies? MyProtocol] as part of core malli functionality? i'd be happy to submit a PR for that, since it seems like this class feature is ready to ship.

@NoahTheDuke
Copy link
Contributor Author

satisfies? is incredibly slow: blog post, Ask, Jira ticket

Given Malli's performance goals, I don't know if a :satisfies? would work well here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
Status: No status
Development

No branches or pull requests

3 participants