Skip to content
This repository has been archived by the owner on Jan 20, 2025. It is now read-only.
xsc edited this page Apr 20, 2013 · 9 revisions

You can import a Thrift struct/type using either thrift-clj.core/import-types or thrift-clj.core/import with the :types key:

(require '[thrift-clj.core :as thrift])
(thrift/import-types [org.example Person Name])

;; or:
(thrift/import
  (:types [org.example Person Name]))

Structs

Say Person is defined like this:

struct Person {
  1: optional string firstName,
  2: string lastName,
  3: byte age
}

Importing it will create a new Clojure record type of the same name in an auto-generated namespace (don't worry about that), then import the type directly into the namespace you currently reside in. It's fields will have the same names as the struct's, and they will be ordered as given in the Thrift definition.

So, to create a new Person (the Clojure type, not the Thrift one), you can use a simple constructor call:

(def some-one (Person. "Some" "One" 99))

Clojure will not complain if you leave out a non-optional field - only when you try to convert a value to its Thrift pendant will you see an exception:

(thrift/->thrift some-one)              ; => #<org.example.Person ...>
(thrift/->thrift (Person. nil nil nil)) ; => Exception: Not an optional field: lastName

Actually, Thrift's Java code would allow for lastName to be null, falling apart only when trying to serialize the value. thrift-clj tries to catch errors like this while still in the Clojure domain.

Although probably needed less often, the reverse conversion is possible, too:

(def p (doto (org.example.Person. "One" 99)
         (.setFirstName "Some")))
(thrift/->clj p) ; => #ns_1071852349.Person{ ... }

Enums

Enums are imported directly, no wrapping is done.

enum Country { US, GB, DE, AT }

This can be used as always:

Country/US                   ; => #<thriftclj.structs.Country US>
(thrift/->thrift Country/US) ; => #<thriftclj.structs.Country US>
(thrift/->clj Country/US)    ; => #<thriftclj.structs.Country US>

Conversion does not touch it, as you can see.

Exceptions

Exceptions are imported as Structs. You have to throw them using thrift-clj.core/throw and can catch them using a thrift-clj.core/try block.

exception SomeError {
  1: byte status,
  2: string msg
}

Usage as follows:

(thrift/import-types [org.example SomeError])

(thrift/try
  ...
  (thrift/throw (SomeError. 1 "Unknown Error"))
  ...
  (catch SomeError {:keys[status msg]}
    (println "[Exception]" msg (str "(" status ")"))))
Clone this wiki locally