├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── bin └── release ├── project.clj ├── src └── outpace │ └── remote │ └── service.cljc └── test └── outpace └── remote └── service_test.cljc /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | .idea 11 | .DS_Store 12 | remote.iml -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 0.4.3 2 | 3 | - Upgraded dependencies (required for Clojure 1.8) 4 | see https://groups.google.com/forum/#!msg/clojure/LT7vDT6fWxA/ol_BC_Fbt7MJ 5 | 6 | # 0.4.2 7 | 8 | - Fixed a defservice bug in CLJS where requests with params were not passing 9 | params. 10 | 11 | # 0.4.0 12 | 13 | - Switch to using Clojure 1.7's reader conditionals instead of cljx. 14 | - Bump Clojure dependency to 1.7. 15 | - Bump ClojureScript dependency to 0.0-2268. 16 | - Fixes bug where channel not always closed when finished. 17 | 18 | # 0.3.1 19 | 20 | - Initial public release. 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Remote 2 | 3 | A Clojure(Script) library and DSL for building client to remote service 4 | APIs. 5 | 6 | ## Usage 7 | 8 | Add the following dependency to your `project.clj` file: 9 | 10 | [![Clojars Project](http://clojars.org/com.outpace/remote/latest-version.svg)](http://clojars.org/com.outpace/remote) 11 | 12 | `[com.outpace/remote "0.3.1"]` is the last version that uses cljx 13 | instead of Clojure 1.7's reader conditionals. If you are on Clojure < 14 | 1.7 you'll need to use this version. 15 | 16 | ## DSL 17 | 18 | ### Endpoint definitions 19 | 20 | ```clj 21 | ;; The url-template specifies that a map containing the key :id must 22 | ;; be passed to render the url. 23 | (defendpoint find-user-by-id "/users/:id" 24 | ;; You *must* specify the HTTP request method for each endpoint. Remote 25 | ;; does not make assumptions or choose so-called "sane" 26 | ;; defaults. 27 | (method :get) 28 | 29 | ;; Set the default headers for each HTTP request made by this endpoint 30 | ;; function. 31 | (headers {"X-Foo" "bar"}) 32 | 33 | ;; The on-request clause creates the function to be called upon each 34 | ;; request allowing you to transform it before it is sent. The arity 35 | ;; of this function must be at least 1 and the first argument will 36 | ;; always be the request map. Any additional arities in this signature 37 | ;; are the arguments following the template parameters argument (the 38 | ;; first) for the returned endpoint function. 39 | (on-request [req query-params] 40 | (assoc req :query-params query-params)) 41 | 42 | ;; The on-status clause allows you to configure per-status response 43 | ;; handlers for each HTTP status code. 44 | (on-status 45 | ;; Here we transform the response value before placing it on the 46 | ;; output channel returned by making a request to this endpoint. 47 | (200 [{:keys [body] :as resp}] 48 | body) 49 | ;; Returning nil will automatically close the output channel. 50 | (500 [_] nil))) 51 | ``` 52 | 53 | This endpoint function can now be called with: 54 | 55 | ```clj 56 | ;; The first argument is the template parameters for the url 57 | ;; template. The second argument is the query-params argument from the 58 | ;; on-request handler we created. 59 | (find-user-by-id {:id 1} {:keys "name,email"}) 60 | ;; => cljs.core.async.impl.channels.ManyToManyChannel 61 | ``` 62 | 63 | ### Service definitions 64 | 65 | ```clj 66 | (defservice user-service 67 | (headers {"X-Foo" "bar"}) 68 | 69 | ;; The on-status clause allows you to configure per-status response 70 | ;; handlers for each endpoint. 71 | (on-status 72 | ;; Always put the data we recieved on the output channel to avoid 73 | ;; repetitous code. 74 | (200 [{:keys [body]}] 75 | body) 76 | (403 [_] 77 | (navigate-to-authentication!))) 78 | 79 | ;; The endpoint clause allows you to configure service endpoints. 80 | (endpoint :all "/users" 81 | (method :get)) 82 | 83 | (endpoint :search "/users/search" 84 | (method :get) 85 | ;; headers, on-request, and on-status work exactly like they do in 86 | ;; defendpoint. Here they are scoped to the :search endpoint. Map 87 | ;; values such as the ones given by headers and on-status are merged 88 | ;; with the default values specified in the root scope of the 89 | ;; defservice block. 90 | (headers {"X-Foo" nil ;; Remove the X-Foo header. 91 | "X-Bar" "baz"}) ;; Add the X-Bar header. 92 | (on-request [req query-params] 93 | (assoc req :query-params query-params)))) 94 | ``` 95 | 96 | This service can now be called with: 97 | 98 | ```clj 99 | ;; Like the endpoint function except we pass the endpoint name as the 100 | ;; first argument. 101 | (user-service :search {} {:name "bill"}) 102 | ;; => cljs.core.async.impl.channels.ManyToManyChannel 103 | ``` 104 | 105 | ## Contributing 106 | 107 | - Add message to CHANGELOG.md under top `#NEXT` section describing 108 | change. 109 | - PRs with tests have a better chance of being accepted. 110 | 111 | ## Releasing 112 | 113 | 1. Set vesion number in `project.clj` to be version you want released 114 | with a `-SNAPSHOT` suffix. 115 | 1. Run `bin/release`. 116 | 117 | ## Contributors (alphabetical) 118 | 119 | - [Alex Rutkowski](https://github.com/alexmarie) 120 | - [Alex Verkhovsky](https://github.com/alexeyv) 121 | - [Alexander Taggart](https://github.com/ataggart) 122 | - [Carin Meier](https://github.com/gigasquid) 123 | - [Case Nelson](https://github.com/snoe) 124 | - [Creighton Kirkendall](https://github.com/ckirkendall) 125 | - [Eli Naeher](https://github.com/enaeher) 126 | - [Francisco Viramontes](https://github.com/kidpollo) 127 | - [Jake McCrary](https://github.com/jakemcc) 128 | - [Joel Holdbrooks](https://github.com/noprompt) 129 | - [Josh Headapohl](https://github.com/joshhead) 130 | 131 | ## License 132 | 133 | Copyright © Outpace 134 | 135 | Released under the Apache License, Version 2.0. 136 | -------------------------------------------------------------------------------- /bin/release: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 4 | pushd "$DIR/.." >/dev/null 5 | 6 | set -e 7 | set -x 8 | 9 | function version { 10 | grep defproject project.clj | cut -f 3 -d ' ' | sed 's/"//g' 11 | } 12 | 13 | function project_name { 14 | grep defproject project.clj | cut -f 2 -d ' ' 15 | } 16 | 17 | lein clean 18 | lein change version leiningen.release/bump-version release 19 | release_version=$(version) 20 | tag_name="$(project_name)-v${release_version}" 21 | 22 | echo "committing + tagging" 23 | git commit -avm "Preparing for release $(project_name) ${release_version}" 24 | git tag -a $tag_name -m "Release $(project_name) v${release_version}" 25 | git push --tags 26 | 27 | lein change version leiningen.release/bump-version 28 | echo "Starting development on $(version)" 29 | git commit -avm "Starting development on $(project_name) $(version)" 30 | git push 31 | 32 | git checkout $tag_name 33 | lein deploy 34 | git checkout master 35 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject com.outpace/remote "0.4.4-SNAPSHOT" 2 | :description "A Clojure(Script) library and DSL for building client to remote service APIs." 3 | 4 | :url "http://github.com/outpace/remote" 5 | :license {:name "Apache License, Version 2.0" 6 | :url "http://www.apache.org/licenses/LICENSE-2.0.html"} 7 | 8 | :dependencies 9 | [[org.clojure/clojure "1.8.0"] 10 | [org.clojure/clojurescript "1.7.228" :scope "provided"] 11 | [org.clojure/core.async "0.2.374"] 12 | [cljs-http "0.1.39"] 13 | [clj-http "2.1.0"]] 14 | 15 | :cljsbuild 16 | {:test-commands {"unit" ["phantomjs" :runner "target/main.js"]} 17 | :builds [{:source-paths ["test"] 18 | :compiler {:output-to "target/main.js" 19 | :optimizations :simple 20 | :pretty-print true}}]} 21 | 22 | :profiles 23 | {:dev {:plugins [[lein-cljsbuild "1.1.3"] 24 | [com.cemerick/clojurescript.test "0.3.3"]] 25 | :auto-clean false 26 | :aliases {"deploy" ["do" "clean," "deploy" "clojars"] 27 | "cleantest" ["do" "clean," "test" "outpace.remote.service-test," "cljsbuild" "test"]}}}) 28 | -------------------------------------------------------------------------------- /src/outpace/remote/service.cljc: -------------------------------------------------------------------------------- 1 | (ns outpace.remote.service 2 | #?(:clj (:require [clojure.walk :as walk] 3 | [clojure.core.async :as async :refer [go]] 4 | [clj-http.client :as http] 5 | [clojure.string :as string])) 6 | #?@(:cljs 7 | [(:require [cljs-http.client :as http] 8 | [cljs.core.async :as async] 9 | [clojure.string :as string]) 10 | (:require-macros 11 | [cljs.core.async.macros :refer [go]])])) 12 | 13 | 14 | ;; --------------------------------------------------------------------- 15 | ;; Utilities 16 | 17 | #?(:clj 18 | (defn template 19 | "Return a string template fn from s." 20 | ([s] 21 | (template s {:regex #":([a-z_-]+)"})) 22 | ([s {:keys [regex]}] 23 | (fn [m] 24 | (string/replace s regex 25 | (fn a-replace [match] 26 | (let [k (keyword (last match)) 27 | v (get m k)] 28 | (if v 29 | (str v) 30 | (throw (Exception. (str "Template variable " k " missing")))))))))) 31 | :cljs 32 | (defn template 33 | "Return a string template fn from s." 34 | ([s] 35 | (template s {:regex #":([a-z_-]+)"})) 36 | ([s {:keys [regex]}] 37 | (fn [m] 38 | (string/replace s regex 39 | (fn a-replace [[$0 $1]] 40 | (let [k (keyword $1) 41 | v (get m k)] 42 | (if v 43 | (str v) 44 | (throw (js/Error. (str "Template variable " $1 " missing"))))))))))) 45 | 46 | (def method->http-fn 47 | {:get http/get 48 | :put http/put 49 | :post http/post 50 | :delete http/delete 51 | :options http/options 52 | :patch http/patch 53 | :head http/head}) 54 | 55 | (defn service-spec? 56 | [spec] 57 | (contains? spec :endpoints)) 58 | 59 | (defn add-headers 60 | [spec headers] 61 | {:pre [(map? spec) (map? headers)]} 62 | (assoc spec :headers headers)) 63 | 64 | (defn add-method 65 | [spec method] 66 | {:pre [(map? spec) (keyword? method)]} 67 | (if (service-spec? spec) 68 | spec 69 | (assoc spec :method method))) 70 | 71 | (defn add-on-request 72 | [spec f] 73 | {:pre [(map? spec) (ifn? f)]} 74 | (assoc spec :on-request f)) 75 | 76 | (defn add-on-status 77 | [spec m] 78 | {:pre [(map? spec) (map? m)]} 79 | (assoc spec :on-status m)) 80 | 81 | (defn add-on-exception 82 | [spec f] 83 | {:pre [(map? spec) (ifn? f)]} 84 | (assoc spec :on-exception f)) 85 | 86 | (defn add-endpoint 87 | [spec key endpoint-config] 88 | {:pre [(service-spec? spec) 89 | (keyword? key) 90 | (map? endpoint-config)]} 91 | (assoc-in spec [:endpoints key] endpoint-config)) 92 | 93 | #?(:clj 94 | (defn url-call [http-fn url req] 95 | (let [result-chan (async/chan)] 96 | (async/put! result-chan (http-fn url req)) 97 | result-chan)) 98 | :cljs 99 | (defn url-call [http-fn url req] 100 | (http-fn url req))) 101 | 102 | 103 | ;; --------------------------------------------------------------------- 104 | ;; Endpoint construction 105 | 106 | (defn- valid-status-key? 107 | [key] 108 | (or (integer? key) (= :default key))) 109 | 110 | (defn make-endpoint 111 | [{:keys [method 112 | url-template 113 | on-request 114 | on-status 115 | on-exception 116 | headers 117 | username 118 | password] 119 | :or {on-request identity 120 | on-status {} 121 | on-exception identity 122 | headers {}} 123 | :as opts}] 124 | (assert (method->http-fn method) 125 | (str ":method must be one of " (keys method->http-fn))) 126 | (assert (string? url-template) 127 | ":url-template must be a string") 128 | (assert (ifn? on-request) 129 | ":on-request is not a function") 130 | (assert (and (map? on-status) 131 | (every? (fn [[k v]] 132 | (and (valid-status-key? k) (ifn? v))) 133 | on-status)) 134 | ":on-status is not a map of {integer ifn}") 135 | (let [http-fn (method->http-fn method) 136 | t (template url-template)] 137 | (fn a-endpoint [template-params & args] 138 | (let [url (t template-params) 139 | cljs-http-opts (-> opts 140 | (assoc :headers headers) 141 | (dissoc :method :url-template :on-request :on-status :on-exception)) 142 | req (apply on-request cljs-http-opts args) 143 | out (async/chan 1) 144 | resp-ch (url-call http-fn url req)] 145 | (go 146 | (try 147 | (let [{:keys [status] :as resp} (async/ endpoint-spec# ~@config))))) 276 | 277 | #?(:clj 278 | (defmacro defendpoint 279 | "Shorthand syntax for defining and endpoint and configuring it. 280 | 281 | Ex. 282 | 283 | (defendpoint all \"/users\" 284 | (method :get) 285 | 286 | (on-status 287 | (200 [{:keys [body]}] 288 | (let [c (count (:body resp))] 289 | (js/console.log c \"USERS FOUND\"))))) 290 | " 291 | [sym url-template & body] 292 | `(def ~sym 293 | (make-endpoint (-> {:url-template ~url-template} ~@body))))) 294 | 295 | #?(:clj 296 | (defmacro defservice 297 | "Shorthand syntax for defining a service and configuring it. 298 | 299 | Ex. 300 | 301 | (defservice user-service 302 | (on-status 303 | (200 [_] 304 | (js/console.log \"SUCCESS\"))) 305 | (endpoint :all \"/users\" 306 | (method :get))) 307 | " 308 | [sym & body] 309 | (let [spec (walk/macroexpand-all `(-> {:endpoints {}} ~@body))] 310 | `(def ~sym (make-service ~spec))))) 311 | -------------------------------------------------------------------------------- /test/outpace/remote/service_test.cljc: -------------------------------------------------------------------------------- 1 | (ns outpace.remote.service-test 2 | #?(:clj (:require [cemerick.cljs.test :refer [block-or-done]] 3 | [clojure.core.async :as async :refer [go]] 4 | [clojure.test :refer :all] 5 | [outpace.remote.service :as service :refer [defendpoint 6 | defservice 7 | headers 8 | endpoint 9 | method 10 | on-status 11 | on-request]])) 12 | #?@(:cljs 13 | [(:require [cemerick.cljs.test] 14 | [cljs.core.async :as async] 15 | [cljs-http.client :as http] 16 | [outpace.remote.service :as service]) 17 | (:require-macros [cemerick.cljs.test :refer [is are deftest run-tests testing block-or-done]] 18 | [cljs.core.async.macros :refer [go]] 19 | [outpace.remote.service :refer [defendpoint 20 | defservice 21 | headers 22 | endpoint 23 | method 24 | on-status 25 | on-request]])])) 26 | 27 | (defservice search-service 28 | (on-status 29 | (200 [body] 30 | body) 31 | (500 [_] nil)) 32 | 33 | (endpoint :repos "https://api.github.com/users" 34 | (method :get) 35 | (on-request [req] 36 | (assoc req :with-credentials? false)))) 37 | 38 | ;; We are testing a real enpoint because we had problems 39 | ;; doing with-redefs in ClojureScript :( 40 | (deftest ^:async async-service-test 41 | (let [complete (async/chan)] 42 | (go (is (= 200 43 | (:status (async/! complete true)) 45 | (block-or-done complete))) 46 | 47 | (deftest failing-on-request-test 48 | (testing "failing on-request handler" 49 | (let [spec {:method :get 50 | :url-template "https://api.github.com/users" 51 | :on-request 52 | (fn [req] 53 | (assoc req :with-credentials? false) 54 | (throw (ex-info "TESTS ARE DOCS!" {:fact "A test is not a doc."}))) 55 | :on-status 56 | {200 identity 57 | 500 identity}} 58 | svc (service/make-endpoint spec)] 59 | (is (thrown? #?(:clj Exception :cljs js/Error) (svc {})))))) 60 | 61 | (deftest ^:async async-failing-on-status-test 62 | (testing "failing on-status handler" 63 | (let [complete (async/chan 1) 64 | ex-chan (async/chan 1) 65 | spec {:method :get 66 | :url-template "https://api.github.com/users" 67 | :on-request 68 | (fn [req] 69 | (assoc req :with-credentials? false)) 70 | :on-exception 71 | (fn [ex] 72 | (async/put! ex-chan ex)) 73 | :on-status 74 | {200 (fn [resp] 75 | (throw (ex-info "TESTS ARE DOCS!" {:fact "A test is not a doc."})) 76 | resp) 77 | 500 identity}} 78 | svc (service/make-endpoint spec)] 79 | (go 80 | (svc {}) 81 | (is (instance? #?(:clj Exception :cljs js/Error) (async/! complete true)) 83 | (block-or-done complete)))) 84 | 85 | (deftest template-test 86 | (testing "template function should work" 87 | (is (= "/user/4" ((service/template "/user/:user_id") {:user_id 4}))))) 88 | --------------------------------------------------------------------------------