├── .gitignore ├── LICENSE ├── README.md ├── project.clj └── src └── clj_zendesk ├── apps.clj ├── core.clj └── util.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 | -------------------------------------------------------------------------------- /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 | # clj-zendesk 2 | 3 | A client for the [Zendesk REST API](https://developer.zendesk.com/rest_api/docs/core/introduction). PRs, feature requests and bug reports very welcome! 4 | 5 | Check out this [extensively annotated source code / documentation](http://atroche.github.io/clj-zendesk). 6 | 7 | It currently only supports the following operations: 8 | 9 | * ```create``` 10 | * ```get``` (aka “show”) 11 | * `get-all` (aka “list”) 12 | * `delete` 13 | 14 | …on the following resources: tickets, views, ticket fields, users, macros, automations, triggers, targets, user fields and groups. 15 | 16 | Don't worry, more resources and endpoints are coming soon — this is mainly a one-hundred-lines-of-code, hacked-together-in-an-afternoon proof-of-concept. But there's still lots of stuff you could build with it. 17 | 18 | The library takes care of turning your idiomatic Clojure data (e.g. ```{:custom-field {:id 20 :value 13}}```) into the format that the API is expecting (e.g. ```{"custom_field": {"id": 20, "value": 13}}```). Your app doesn't need to deal with JSON or hyphens-vs-underscores or any of those boring things! 19 | 20 | Currently only supports auth-ing via OAuth token. 21 | 22 | ## Installation 23 | 24 | Just add ```[clj-zendesk "0.1.0"]``` to `:dependencies` in your project's `profile.clj`. 25 | 26 | ## Usage 27 | 28 | ```clojure 29 | user> (use 'clj-zendesk.core) 30 | user> (setup "zendesk_subdomain" "zendesk.com" "zendesk_email@zendesk.com" "YOURAPITOKEN") 31 | user> (get-all Users) 32 | [{:role "end-user", :updated-at "2013-11-29T00:16:30Z", :tags [], :email "end@user.com", :chat-only false, … etc. 33 | 34 | 35 | user=> (def my-new-ticket (create Ticket {:subject "Help me!" :comment {:body "my app is broken!"} })) 36 | {:description "my app is broken!", :updated-at "2014-12-19T08:48:11Z", :assignee-id nil, :tags [], :custom-fields [{:id 24146696, :value nil} {:id 24099383, :value nil} {:id 24056003, :value nil}], :group-id 21407398, :via {:channel "api", :source {:from {}, :to {}, :rel nil}}, :has-incidents false, :fields [{:id 24146696, :value nil} {:id 24099383, :value nil} {:id 24056003, :value nil}], :recipient nil, :type nil, :organization-id 29244208, :sharing-agreement-ids [], :requester-id 533561168, :external-id nil, :satisfaction-rating nil, :priority nil, :status "new", :id 12, :problem-id nil, :ticket-form-id nil, :url "https://zendesk_subdomain.zendesk.com/api/v2/tickets/12.json", :collaborator-ids [], :raw-subject "Help me!", :created-at "2014-12-19T08:48:11Z", :subject "Help me!", :forum-topic-id nil, :due-at nil, :submitter-id 533561168} 37 | 38 | user=> (:id my-new-ticket) 39 | 12 40 | 41 | user=> (get-one Ticket 12) 42 | {:description "my app is broken!", :updated-at "2014-12-19T08:48:11Z", :assignee-id nil, :tags [], :custom-fields [{:id 24146696, :value nil} {:id 24099383, :value nil} {:id 24056003, :value nil}], :group-id 21407398, :via {:channel "api", :source {:from {}, :to {}, :rel nil}}, :has-incidents false, :fields [{:id 24146696, :value nil} {:id 24099383, :value nil} {:id 24056003, :value nil}], :recipient nil, :type nil, :organization-id 29244208, :sharing-agreement-ids [], :requester-id 533561168, :external-id nil, :satisfaction-rating nil, :priority nil, :status "new", :id 12, :problem-id nil, :ticket-form-id nil, :url "https://zendesk_subdomain.zendesk.com/api/v2/tickets/12.json", :collaborator-ids [], :raw-subject "Help me!", :created-at "2014-12-19T08:48:11Z", :subject "Help me!", :forum-topic-id nil, :due-at nil, :submitter-id 533561168} 43 | ``` 44 | 45 | Rinse and repeat for Users, TicketFields, Macros, etc., etc. 46 | 47 | ## License 48 | 49 | Copyright © 2014-2015 Alistair Roche 50 | 51 | Distributed under the Eclipse Public License either version 1.0 or (at 52 | your option) any later version. 53 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject clj-zendesk "0.3.0-SNAPSHOT" 2 | :description "Zendesk REST API client for Clojure" 3 | :url "https://github.com/atroche/clj-zendesk" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :plugins [[lein-marginalia "0.8.0"]] 7 | :dependencies [[org.clojure/clojure "1.6.0"] 8 | [clj-http "1.0.1"] 9 | [inflections "0.9.13"] 10 | [com.cemerick/url "0.1.1"] 11 | [org.clojure/tools.trace "0.7.8"] 12 | [camel-snake-kebab "0.2.5" :exclusions [org.clojure/clojure]] 13 | [cheshire "5.4.0"]]) 14 | -------------------------------------------------------------------------------- /src/clj_zendesk/apps.clj: -------------------------------------------------------------------------------- 1 | (ns clj-zendesk.apps 2 | (:require [clj-http.client :refer [request post] :as http] 3 | [clj-zendesk.core :refer [api-call setup auth-creds api-url] :as api] 4 | [clj-zendesk.util :refer [map-all-keys]] 5 | [inflections.core :refer [singular plural capitalize]] 6 | [cemerick.url :as url] 7 | [camel-snake-kebab.core :refer [->kebab-case ->snake_case 8 | ->CamelCase]] 9 | [cheshire.core :refer [generate-string parse-string]])) 10 | 11 | 12 | (defn upload-new-app-package 13 | "Upload a new zip file package for an app. 14 | Returns an upload id which can be used to create or update an app." 15 | [app-zip-path] 16 | (let [response (post (str api-url "apps/uploads.json") 17 | {:basic-auth auth-creds 18 | :multipart [{:name "uploaded_data" 19 | :mime-type "application/octet-stream" 20 | :content (clojure.java.io/file app-zip-path)}]})] 21 | (-> response 22 | :body 23 | (parse-string true) 24 | :id))) 25 | 26 | (defn create-app 27 | "Takes upload ID, enqueues app creation, returns job id" 28 | [upload-id app-name short-description] 29 | (let [response (post (str api-url "apps.json") 30 | {:basic-auth auth-creds 31 | :body ()})] 32 | (-> response 33 | :body 34 | (parse-string true) 35 | :id))) 36 | 37 | (defn get-job-status 38 | "Takes upload ID, enqueues app creation, returns job id" 39 | [job-id] 40 | (let [response (http/get (str api-url (str "job_statuses/" job-id ".json")) 41 | {:basic-auth auth-creds})] 42 | (-> response 43 | :body 44 | (parse-string true)))) 45 | 46 | (api-call :post "apps.json" nil {:name "RQO via API" 47 | :short-description "this is via the API" 48 | :upload-id 5487}) 49 | 50 | (setup "alistair-pod101" "aroche@zendesk.com" "HAdMqK6wHALLIRaVxxTdvYq6zXiZOrSsKCV0bO5Z") 51 | 52 | 53 | (api/defresource :apps {:includes-root-element true}) 54 | 55 | 56 | (upload App zip-file) 57 | (create App upload-id) 58 | (update App app-id data) 59 | (get App id) 60 | (get-all Apps) 61 | (delete App id) 62 | (notify App {:event "whatever" :app-id 3}) 63 | 64 | (api/defsubresource :apps :job-statuses) 65 | (get AppJobStatus job-id) 66 | 67 | 68 | (api/subresource :apps :installations) 69 | 70 | (get-all AppInstallations {:include :app}) 71 | (create AppInstallation {:app-id 1 :settings {:name "blah"}}) 72 | (get-one AppInstallation 10) 73 | (update AppInstallation 1) 74 | (delete AppInstallation 3) 75 | 76 | (api/subresource :apps :installations :job-statuses) 77 | (get-one AppInstallationJobStatus job-id) 78 | 79 | (api/subresource :apps :installations :requirements) 80 | (get-all AppInstallationRequirements) 81 | -------------------------------------------------------------------------------- /src/clj_zendesk/core.clj: -------------------------------------------------------------------------------- 1 | ;; ## A Zendesk API client for Clojure 2 | 3 | ;; The Zendesk has a fairly massive and complex API. It can be hard to get your head around 4 | ;; and use. There's a brilliant client for Ruby, but what about for the Clojure community? 5 | ;; clj-zendesk is the answer. 6 | 7 | ;; ## A warning 8 | 9 | ;; This project is still new and incomplete. It supports basic functionality at this point, 10 | ;; but still doesn't even support a majority of the endpoints. 11 | 12 | ;; ## Credits 13 | 14 | ;; Inspiration for the design of the API call mechanism comes from Raynes' excellent tenctacles library. 15 | 16 | (ns clj-zendesk.core 17 | (:require [clj-http.client :refer [request]] 18 | [clj-zendesk.util :refer [map-all-keys kebabify-map underscorify-map]] 19 | [inflections.core :refer [singular plural capitalize]] 20 | [cemerick.url :as url] 21 | [camel-snake-kebab.core :refer [->snake_case ->CamelCase]] 22 | [cheshire.core :refer [generate-string parse-string]])) 23 | 24 | 25 | (def ^:dynamic defaults {:domain "zendesk.com" 26 | :subdomain nil 27 | :email nil 28 | :token nil}) 29 | 30 | (defmacro with-defaults 31 | [options & body] 32 | `(binding [defaults ~options] 33 | ~@body)) 34 | 35 | (defn format-url 36 | "Creates a URL out of end-point and positional-args (i.e. values to put in the URL). 37 | URL encodes the elements of positional-args and then formats them in. 38 | 39 | E.g. `(format-url \"/users/%s.json\" [3]) returns \"/users/3.json\"" 40 | [end-point positional-args] 41 | (let [{:keys [subdomain domain]} defaults 42 | api-url 43 | (format "https://%s.%s/api/v2/" subdomain domain)] 44 | (str api-url (apply format end-point (map url/url-encode positional-args))))) 45 | 46 | (defn make-request 47 | "Prepares a map representing a request for passing into `clj-http.client/request` 48 | in our `api-call` function. 49 | 50 | Combines the passed in URL args and form data with some basic defaults for headers." 51 | [{:keys [method end-point positional-args query url]}] 52 | (let [{:keys [email token]} defaults 53 | auth-creds [(str email "/token") token] 54 | req {:url (or url 55 | (format-url (str end-point ".json") positional-args)) 56 | :basic-auth auth-creds 57 | :accept :json 58 | :content-type :json 59 | :method (or method :get)} 60 | underscorified-query (underscorify-map query) 61 | form-or-query-params (if (#{:post :put :delete} method) 62 | :form-params 63 | :query-params) 64 | req (assoc req form-or-query-params underscorified-query)] 65 | (-> req request 66 | :body 67 | (parse-string true) 68 | kebabify-map))) 69 | 70 | 71 | (defn api-call 72 | "Actually make the HTTP request. 73 | 74 | Parses the JSON in the response body and turns the underscored keys 75 | back into kebab-case." 76 | ([method end-point] (api-call method end-point nil {})) 77 | ([method end-point positional-args] (api-call method end-point positional-args {})) 78 | ([method end-point positional-args query] 79 | (make-request {:method method 80 | :end-point end-point 81 | :positional-args positional-args 82 | :query (or query {})}))) 83 | 84 | 85 | (defprotocol StandardOperations 86 | "Many resources have a standard range of things you can do with them (CRUD, basically)." 87 | (get-all [_]) 88 | (get-one [_ id]) 89 | (create-one [_ data]) 90 | (update-one [_ id data]) 91 | (delete-one [_ id])) 92 | 93 | (defn base-url 94 | "Takes in e.g. :users and returns \"users\". Or :ticket-fields and 95 | returns \"ticket_fields\". 96 | 97 | So we can refer to resources using keywords but then use those when resolving endpoints." 98 | [resource-name] 99 | 100 | (-> resource-name 101 | name 102 | ->snake_case)) 103 | 104 | ;; Represents an API resource like “tickets” or “users”. 105 | ;; 106 | ;; Implements the standard operations which, thanks to the fairly consistent 107 | ;; API means that we can reuse the same basic code for CRUD operations 108 | ;; across a wide range of resources. 109 | 110 | ;; `get-all` corresponds to a GET on the root of a resource (e.g. /api/v2/users.json) 111 | 112 | ;; `get-one` corresponds to a GET on a specific resource (e.g. /api/v2//users/3.json) 113 | 114 | ;; `create` corresponds to a POST on the root of a resource (e.g. /api/v2/users.json) 115 | 116 | ;; `delete` corresponds to a GET on a specific resource (e.g. /api/v2//users/3.json) 117 | 118 | ;; I haven't implemented `update` yet because I forgot and haven't had time! 119 | (defrecord Resource 120 | [resource-name] 121 | StandardOperations 122 | 123 | (get-all [_] 124 | (let [initial-response (api-call :get (base-url resource-name)) 125 | ; better with letfn? 126 | handle-pagination (fn handle-pages [resp] 127 | (let [next-page (:next-page resp) 128 | resources ((plural resource-name) resp)] 129 | (if next-page 130 | (lazy-cat resources 131 | (handle-pages (make-request {:url next-page}))) 132 | resources)))] 133 | (handle-pagination initial-response))) 134 | (get-one [_ id] 135 | ((singular resource-name) (api-call :get (str (base-url resource-name) "/%s") [id]))) 136 | (create-one [_ data] 137 | ((singular resource-name) (api-call :post 138 | (base-url resource-name) 139 | nil 140 | {(singular resource-name) data}))) 141 | (delete-one [_ id] 142 | (api-call :delete (str (base-url resource-name) "/%s") [id]))) 143 | 144 | 145 | (defmacro defresource 146 | "Takes e.g. :ticket-fields and will create the following `Resources`: TicketField and TicketFields. This is so we can do (get-one TicketField ) as well as (get-all TicketFields), which just makes the whole thing read nice. 147 | " 148 | [resource-name] 149 | (let [resource-symbol# `~(-> resource-name 150 | name 151 | ->CamelCase 152 | symbol) 153 | singular-symbol# `~(singular resource-symbol#)] 154 | `(do 155 | (def ~resource-symbol# 156 | (->Resource ~resource-name)) 157 | (def ~singular-symbol# 158 | ~resource-symbol#)))) 159 | 160 | 161 | (defmacro defresources 162 | "Takes a bunch of resource names and does defresource on all of them. 163 | 164 | E.g. `(defresource :tickets :users)` becomes `(do (defresource :tickets) (defresource :users))`" 165 | [& args] 166 | `(do 167 | ~@(for [resource args] 168 | `(defresource ~resource)))) 169 | 170 | 171 | ;; Define a bunch of resources. These are ones where standard operations Just Work™ 172 | ;; out of the box. There are probably more, I just haven't bothered to check and add them :) 173 | 174 | ;; Good news is that if there's one you want to use you can just do `(defresource :my-new-resource)` and you'll be able to e.g. `(get-all MyNewResources)`. Or you could just add it to the list below and make a pull request =) 175 | (defresources :tickets 176 | :views 177 | :ticket-fields 178 | :users 179 | :macros 180 | :automations 181 | :triggers 182 | :targets 183 | :user-fields 184 | :groups) 185 | 186 | -------------------------------------------------------------------------------- /src/clj_zendesk/util.clj: -------------------------------------------------------------------------------- 1 | (ns clj-zendesk.util 2 | (:require [clojure.walk :refer [postwalk]] 3 | [camel-snake-kebab.core :refer [->snake_case ->kebab-case]])) 4 | 5 | (defn map-all-keys 6 | "Recursively transforms all map keys from snake_case to kebab-case" 7 | [f m] 8 | (letfn [(transform-key [[k v]] [(f k) v]) 9 | (transform-maps [form] 10 | (if (map? form) 11 | (into {} (map transform-key form)) 12 | form))] 13 | (postwalk transform-maps m))) 14 | 15 | (def kebabify-map (partial map-all-keys ->kebab-case)) 16 | (def underscorify-map (partial map-all-keys ->snake_case)) 17 | --------------------------------------------------------------------------------