├── .github └── workflows │ └── test.yml ├── .gitignore ├── CHANGELOG.md ├── LICENCE ├── README.md ├── gleam.toml ├── manifest.toml ├── src ├── gleam │ ├── fetch.gleam │ └── fetch │ │ └── form_data.gleam └── gleam_fetch_ffi.mjs └── test ├── gleam_fetch_test.gleam └── polyfills.js /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: 4 | push: 5 | branches: 6 | - "main" 7 | - "v*.*.*" 8 | pull_request: 9 | 10 | jobs: 11 | test: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v3 15 | - uses: actions/setup-node@v2 16 | with: 17 | node-version: "19.3.0" 18 | - uses: erlef/setup-beam@v1 19 | with: 20 | otp-version: false 21 | gleam-version: "1.9.1" 22 | - run: gleam test 23 | - run: gleam format --check src test 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | node_modules 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## v1.3.0 - 2025-03-29 4 | 5 | - Updated for Gleam v1.9.0. 6 | 7 | ## v1.2.0 - 2025-03-20 8 | 9 | - Add support for formdata reading and editing. 10 | 11 | ## v1.1.1 - 2025-02-06 12 | 13 | - Relaxed the `gleam_http` requirement to permit v4. 14 | 15 | ## v1.1.0 - 2024-11-19 16 | 17 | - Support for formdata bodies added. 18 | 19 | ## v1.0.1 - 2024-05-12 20 | 21 | - Internal structural changes. No user facing changes. 22 | 23 | ## v1.0.0 - 2024-04-22 24 | 25 | - Added the `send_bits` function. 26 | 27 | ## v0.4.0 - 2024-03-07 28 | 29 | - Added the `read_bytes_body` function. 30 | 31 | ## v0.3.1 - 2024-01-16 32 | 33 | - Relaxed version constraint on `gleam_stdlib` to permit 0.x or 1.x. 34 | 35 | ## v0.3.0 - 2023-11-06 36 | 37 | - Updated for Gleam v0.32.0. 38 | 39 | ## v0.2.1 - 2023-09-30 40 | 41 | - `gleam_stdlib` is now listed as a direct dependency. 42 | 43 | ## v0.2.0 - 2023-08-03 44 | 45 | - Updated for Gleam v0.30.0. 46 | 47 | ## v0.1.0 - 2022-12-29 48 | 49 | - Initial release 50 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 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 | Copyright 2020, Louis Pilfold . 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | 192 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gleam Fetch 2 | 3 | GitHub release 4 | Discord chat 5 | 6 | Make HTTP requests in Gleam JavaScript with Fetch. 7 | 8 | ```sh 9 | gleam add gleam_fetch@1 gleam_http 10 | ``` 11 | 12 | ```gleam 13 | import gleam/fetch 14 | import gleam/http/request 15 | import gleam/http/response 16 | import gleam/javascript/promise 17 | 18 | pub fn main() { 19 | let assert Ok(req) = request.to("https://example.com") 20 | 21 | // Send the HTTP request to the server 22 | use resp <- promise.try_await(fetch.send(req)) 23 | use resp <- promise.try_await(fetch.read_text_body(resp)) 24 | 25 | // We get a response record back 26 | resp.status 27 | // -> 200 28 | 29 | response.get_header(resp, "content-type") 30 | // -> Ok("text/html; charset=UTF-8") 31 | 32 | promise.resolve(Ok(Nil)) 33 | } 34 | ``` 35 | 36 | Documentation can be found at [https://hexdocs.pm/gleam_fetch](https://hexdocs.pm/gleam_fetch). 37 | 38 | > [!WARNING] 39 | > If you are running your Gleam project on the Erlang target (the default for 40 | > new Gleam projects) then you will want to use a different library which can 41 | > run on Erlang, such as [`gleam_httpc`](https://github.com/gleam-lang/httpc). 42 | -------------------------------------------------------------------------------- /gleam.toml: -------------------------------------------------------------------------------- 1 | name = "gleam_fetch" 2 | version = "1.3.0" 3 | licences = ["Apache-2.0"] 4 | description = "Make HTTP requests in Gleam JavaScript with Fetch" 5 | target = "javascript" 6 | gleam = ">= 1.9.0" 7 | 8 | repository = { type = "github", user = "gleam-lang", repo = "fetch" } 9 | links = [ 10 | { title = "Website", href = "https://gleam.run" }, 11 | { title = "Sponsor", href = "https://github.com/sponsors/lpil" }, 12 | ] 13 | 14 | [dependencies] 15 | gleam_http = ">= 3.1.0 and < 5.0.0" 16 | gleam_javascript = ">= 0.3.0 and < 2.0.0" 17 | gleam_stdlib = ">= 0.32.0 and < 2.0.0" 18 | 19 | [dev-dependencies] 20 | gleeunit = ">= 1.0.0 and < 2.0.0" 21 | -------------------------------------------------------------------------------- /manifest.toml: -------------------------------------------------------------------------------- 1 | # This file was generated by Gleam 2 | # You typically do not need to edit this file 3 | 4 | packages = [ 5 | { name = "gleam_http", version = "4.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_http", source = "hex", outer_checksum = "0A62451FC85B98062E0907659D92E6A89F5F3C0FBE4AB8046C99936BF6F91DBC" }, 6 | { name = "gleam_javascript", version = "1.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_javascript", source = "hex", outer_checksum = "EF6C77A506F026C6FB37941889477CD5E4234FCD4337FF0E9384E297CB8F97EB" }, 7 | { name = "gleam_stdlib", version = "0.54.0", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "723BA61A2BAE8D67406E59DD88CEA1B3C3F266FC8D70F64BE9FEC81B4505B927" }, 8 | { name = "gleeunit", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleeunit", source = "hex", outer_checksum = "0E6C83834BA65EDCAAF4FE4FB94AC697D9262D83E6F58A750D63C9F6C8A9D9FF" }, 9 | ] 10 | 11 | [requirements] 12 | gleam_http = { version = ">= 3.1.0 and < 5.0.0" } 13 | gleam_javascript = { version = ">= 0.3.0 and < 2.0.0" } 14 | gleam_stdlib = { version = ">= 0.32.0 and < 2.0.0" } 15 | gleeunit = { version = ">= 1.0.0 and < 2.0.0" } 16 | -------------------------------------------------------------------------------- /src/gleam/fetch.gleam: -------------------------------------------------------------------------------- 1 | import gleam/dynamic.{type Dynamic} 2 | import gleam/fetch/form_data.{type FormData} 3 | import gleam/http/request.{type Request} 4 | import gleam/http/response.{type Response} 5 | import gleam/javascript/promise.{type Promise} 6 | 7 | /// Fetch errors can be due to a network error or a runtime error. A common 8 | /// mistake is to try to consume the response body twice, or to try to read the 9 | /// response body as JSON while it's not a valid JSON. 10 | /// 11 | /// Take note that a 500 response is not considered as an error: it is a 12 | /// successful request, which indicates the server triggers an error. 13 | pub type FetchError { 14 | /// A network error occured, maybe because user lost network connection, 15 | /// because the network took to long to answer, or because the 16 | /// server timed out. 17 | NetworkError(String) 18 | /// Fetch is unable to read body, for example when body as already been read 19 | /// once. 20 | UnableToReadBody 21 | InvalidJsonBody 22 | } 23 | 24 | pub type FetchBody 25 | 26 | /// Gleam equivalent of JavaScript [`Request`](https://developer.mozilla.org/docs/Web/API/Request). 27 | pub type FetchRequest 28 | 29 | /// Gleam equivalent of JavaScript [`Response`](https://developer.mozilla.org/docs/Web/API/Response). 30 | pub type FetchResponse 31 | 32 | /// Call directly `fetch` with a `Request`, and convert the result back to Gleam. 33 | /// Let you get back a `FetchResponse` instead of the Gleam 34 | /// `gleam/http/response.Response` data. 35 | /// 36 | /// ```gleam 37 | /// request.new() 38 | /// |> request.set_host("example.com") 39 | /// |> request.set_path("/example") 40 | /// |> fetch.to_fetch_request 41 | /// |> fetch.raw_send 42 | /// ``` 43 | @external(javascript, "../gleam_fetch_ffi.mjs", "raw_send") 44 | pub fn raw_send(a: FetchRequest) -> Promise(Result(FetchResponse, FetchError)) 45 | 46 | /// Call `fetch` with a Gleam `Request(String)`, and convert the result back 47 | /// to Gleam. Use it to send strings or JSON stringified. 48 | /// 49 | /// If you're looking for something more low-level, take a look at 50 | /// [`raw_send`](#raw_send). 51 | /// 52 | /// ```gleam 53 | /// let my_data = json.object([#("field", "value")]) 54 | /// request.new() 55 | /// |> request.set_host("example.com") 56 | /// |> request.set_path("/example") 57 | /// |> request.set_body(json.to_string(my_data)) 58 | /// |> request.set_header("content-type", "application/json") 59 | /// |> fetch.send 60 | /// ``` 61 | pub fn send( 62 | request: Request(String), 63 | ) -> Promise(Result(Response(FetchBody), FetchError)) { 64 | request 65 | |> to_fetch_request 66 | |> raw_send 67 | |> promise.try_await(fn(resp) { 68 | promise.resolve(Ok(from_fetch_response(resp))) 69 | }) 70 | } 71 | 72 | /// Call `fetch` with a Gleam `Request(FormData)`, and convert the result back 73 | /// to Gleam. Request will be sent as a `multipart/form-data`, and should be 74 | /// decoded as-is on servers. 75 | /// 76 | /// If you're looking for something more low-level, take a look at 77 | /// [`raw_send`](#raw_send). 78 | /// 79 | /// ```gleam 80 | /// request.new() 81 | /// |> request.set_host("example.com") 82 | /// |> request.set_path("/example") 83 | /// |> request.set_body({ 84 | /// form_data.new() 85 | /// |> form_data.append("key", "value") 86 | /// }) 87 | /// |> fetch.send_form_data 88 | /// ``` 89 | pub fn send_form_data( 90 | request: Request(FormData), 91 | ) -> Promise(Result(Response(FetchBody), FetchError)) { 92 | request 93 | |> form_data_to_fetch_request 94 | |> raw_send 95 | |> promise.try_await(fn(resp) { 96 | promise.resolve(Ok(from_fetch_response(resp))) 97 | }) 98 | } 99 | 100 | /// Call `fetch` with a Gleam `Request(FormData)`, and convert the result back 101 | /// to Gleam. Binary will be sent as-is, and you probably want a proper 102 | /// content-type added. 103 | /// 104 | /// If you're looking for something more low-level, take a look at 105 | /// [`raw_send`](#raw_send). 106 | /// 107 | /// ```gleam 108 | /// request.new() 109 | /// |> request.set_host("example.com") 110 | /// |> request.set_path("/example") 111 | /// |> request.set_body(<<"data">>) 112 | /// |> request.set_header("content-type", "application/octet-stream") 113 | /// |> fetch.send_form_data 114 | /// ``` 115 | pub fn send_bits( 116 | request: Request(BitArray), 117 | ) -> Promise(Result(Response(FetchBody), FetchError)) { 118 | request 119 | |> bitarray_request_to_fetch_request 120 | |> raw_send 121 | |> promise.try_await(fn(resp) { 122 | promise.resolve(Ok(from_fetch_response(resp))) 123 | }) 124 | } 125 | 126 | /// Convert a Gleam `Request(String)` to a JavaScript 127 | /// [`Request`](https://developer.mozilla.org/docs/Web/API/Request), where 128 | /// `body` is a string. 129 | /// 130 | /// Can be used in conjuction with `raw_send`, or when you need to reuse your 131 | /// `Request` in JavaScript FFI. 132 | /// 133 | /// ```gleam 134 | /// let request = 135 | /// request.new() 136 | /// |> request.set_host("example.com") 137 | /// |> request.set_path("/example") 138 | /// fetch.to_fetch_request(request) 139 | /// ``` 140 | @external(javascript, "../gleam_fetch_ffi.mjs", "to_fetch_request") 141 | pub fn to_fetch_request(a: Request(String)) -> FetchRequest 142 | 143 | /// Convert a Gleam `Request(FormData)` to a JavaScript 144 | /// [`Request`](https://developer.mozilla.org/docs/Web/API/Request), where 145 | /// `body` is a JavaScript `FormData` object. 146 | /// 147 | /// Can be used in conjuction with `raw_send`, or when you need to reuse your 148 | /// `Request` in JavaScript FFI. 149 | /// 150 | /// ```gleam 151 | /// let request = 152 | /// request.new() 153 | /// |> request.set_host("example.com") 154 | /// |> request.set_path("/example") 155 | /// |> request.set_body({ 156 | /// form_data.new() 157 | /// |> form_data.append("key", "value") 158 | /// }) 159 | /// fetch.form_data_to_fetch_request(request) 160 | /// ``` 161 | @external(javascript, "../gleam_fetch_ffi.mjs", "form_data_to_fetch_request") 162 | pub fn form_data_to_fetch_request(a: Request(FormData)) -> FetchRequest 163 | 164 | /// Convert a Gleam `Request(BitArray)` to a JavaScript 165 | /// [`Request`](https://developer.mozilla.org/docs/Web/API/Request), where 166 | /// `body` is a JavaScript `UInt8Array` object. 167 | /// 168 | /// Can be used in conjuction with `raw_send`, or when you need to reuse your 169 | /// `Request` in JavaScript FFI. 170 | /// 171 | /// ```gleam 172 | /// let request = 173 | /// request.new() 174 | /// |> request.set_host("example.com") 175 | /// |> request.set_path("/example") 176 | /// |> request.set_body(<<"data">>) 177 | /// fetch.bitarray_request_to_fetch_request(request) 178 | /// ``` 179 | @external(javascript, "../gleam_fetch_ffi.mjs", "bitarray_request_to_fetch_request") 180 | pub fn bitarray_request_to_fetch_request(a: Request(BitArray)) -> FetchRequest 181 | 182 | /// Convert a JavaScript [`Response`](https://developer.mozilla.org/docs/Web/API/Response) 183 | /// into a Gleam `Response(FetchBody)`. Can be used with the result of 184 | /// `raw_send`, or with some data received through the FFI. 185 | /// 186 | /// ```gleam 187 | /// request.new() 188 | /// |> request.set_host("example.com") 189 | /// |> request.set_path("/example") 190 | /// |> fetch.to_fetch_request 191 | /// |> fetch.raw_send 192 | /// |> promise.map_try(fetch.from_fetch_response) 193 | /// ``` 194 | @external(javascript, "../gleam_fetch_ffi.mjs", "from_fetch_response") 195 | pub fn from_fetch_response(a: FetchResponse) -> Response(FetchBody) 196 | 197 | /// Read a response body as a BitArray. Returns an error when the body is not a 198 | /// valid BitArray. Because `fetch.send` returns a `Promise` and every 199 | /// functions to read response body are also asynchronous, take care to properly 200 | /// use `gleam/javascript/promise` to combine them. 201 | /// 202 | /// ```gleam 203 | /// let my_data = json.object([#("field", "value")]) 204 | /// request.new() 205 | /// |> request.set_host("example.com") 206 | /// |> request.set_path("/example") 207 | /// |> request.set_body(json.to_string(my_data)) 208 | /// |> request.set_header("content-type", "application/json") 209 | /// |> fetch.send 210 | /// |> promise.try_await(fetch.read_bytes_body) 211 | /// ``` 212 | @external(javascript, "../gleam_fetch_ffi.mjs", "read_bytes_body") 213 | pub fn read_bytes_body( 214 | a: Response(FetchBody), 215 | ) -> Promise(Result(Response(BitArray), FetchError)) 216 | 217 | /// Read a response body as a String. Returns an error when the body is not a 218 | /// valid String. Because `fetch.send` returns a `Promise` and every 219 | /// functions to read response body are also asynchronous, take care to properly 220 | /// use `gleam/javascript/promise` to combine them. 221 | /// 222 | /// ```gleam 223 | /// let my_data = json.object([#("field", "value")]) 224 | /// request.new() 225 | /// |> request.set_host("example.com") 226 | /// |> request.set_path("/example") 227 | /// |> request.set_body(json.to_string(my_data)) 228 | /// |> request.set_header("content-type", "application/json") 229 | /// |> fetch.send 230 | /// |> promise.try_await(fetch.read_text_body) 231 | /// ``` 232 | @external(javascript, "../gleam_fetch_ffi.mjs", "read_text_body") 233 | pub fn read_text_body( 234 | a: Response(FetchBody), 235 | ) -> Promise(Result(Response(String), FetchError)) 236 | 237 | /// Read a response body as a JSON. Returns an error when the body is not a 238 | /// valid String. Because `fetch.send` returns a `Promise` and every 239 | /// functions to read response body are also asynchronous, take care to properly 240 | /// use `gleam/javascript/promise` to combine them. 241 | /// 242 | /// Once read, you probably want to use 243 | /// [`gleam/dynamic/decode`](https://hexdocs.pm/gleam_stdlib/gleam/dynamic/decode.html) 244 | /// to decode its content in proper Gleam data. 245 | /// 246 | /// ```gleam 247 | /// let my_data = json.object([#("field", "value")]) 248 | /// request.new() 249 | /// |> request.set_host("example.com") 250 | /// |> request.set_path("/example") 251 | /// |> request.set_body(json.to_string(my_data)) 252 | /// |> request.set_header("content-type", "application/json") 253 | /// |> fetch.send 254 | /// |> promise.try_await(fetch.read_json_body) 255 | /// ``` 256 | @external(javascript, "../gleam_fetch_ffi.mjs", "read_json_body") 257 | pub fn read_json_body( 258 | a: Response(FetchBody), 259 | ) -> Promise(Result(Response(Dynamic), FetchError)) 260 | -------------------------------------------------------------------------------- /src/gleam/fetch/form_data.gleam: -------------------------------------------------------------------------------- 1 | //// `FormData` are common structures on the web to send both string data, and 2 | //// blob. They're the default standard when using a `
` on a web page, 3 | //// and they're still a simple way to send files from a frontend to a backend. 4 | //// 5 | //// To simplify management of form data, JavaScript exposes a structure called 6 | //// `FormData` that handles all the complicated details for you. JavaScript 7 | //// `FormData` are compatible with every standards functions, like `fetch` or 8 | //// `xmlHttpRequest`. 9 | //// 10 | //// To maximise compatibility between JavaScript and Gleam, `gleam_fetch` 11 | //// exposes bindings to JavaScript 12 | //// [`FormData`](https://developer.mozilla.org/docs/Web/API/FormData). 13 | 14 | import gleam/javascript/promise.{type Promise} 15 | 16 | /// Form data represents form fields and their values, as a set of key/value 17 | /// pairs. Keys are always strings, while values can be either strings or blob. 18 | /// Form data can be used in conjuction with `fetch`, and uses the same format a 19 | /// form would use with the encoding type were set to `"multipart/form-data"`. 20 | /// Form data can have multiple values for a same key, and those values can be 21 | /// of any type (string or blob). 22 | /// 23 | /// `FormData` are bindings on native JavaScript 24 | /// [`FormData`](https://developer.mozilla.org/docs/Web/API/FormData) object. 25 | /// `FormData` can easily be manipulated with the corresponding functions that 26 | /// ensure correct conversions between JavaScript & Gleam. 27 | pub type FormData 28 | 29 | /// Create a new empty `FormData`. 30 | @external(javascript, "../../gleam_fetch_ffi.mjs", "newFormData") 31 | pub fn new() -> FormData 32 | 33 | /// Append a key/string pair. 34 | /// 35 | /// ```gleam 36 | /// form_data.new() 37 | /// |> form_data.append("key1", "value1") 38 | /// |> form_data.append("key1", "value2") 39 | /// |> form_data.append("key2", "value1") 40 | /// ``` 41 | @external(javascript, "../../gleam_fetch_ffi.mjs", "appendFormData") 42 | pub fn append(form_data: FormData, key: String, value: String) -> FormData 43 | 44 | /// Append a key/bitarray pair. 45 | /// 46 | /// ```gleam 47 | /// form_data.new() 48 | /// |> form_data.append_bits("key1", <<"value1">>) 49 | /// |> form_data.append_bits("key1", <<"value2">>) 50 | /// |> form_data.append_bits("key2", <<"value1">>) 51 | /// ``` 52 | @external(javascript, "../../gleam_fetch_ffi.mjs", "appendBitsFormData") 53 | pub fn append_bits( 54 | form_data: FormData, 55 | key: String, 56 | value: BitArray, 57 | ) -> FormData 58 | 59 | /// Set key/string pair, and replace any existing value for the specified key. 60 | /// 61 | /// ```gleam 62 | /// form_data.new() 63 | /// |> form_data.append("key1", "value1") 64 | /// |> form_data.append_bits("key1", <<"value2">>) 65 | /// |> form_data.set("key1", "value3") 66 | /// ``` 67 | @external(javascript, "../../gleam_fetch_ffi.mjs", "setFormData") 68 | pub fn set(form_data: FormData, key: String, value: String) -> FormData 69 | 70 | /// Set key/bitarray pair, and replace any existing value for the specified key. 71 | /// 72 | /// ```gleam 73 | /// form_data.new() 74 | /// |> form_data.append("key1", "value1") 75 | /// |> form_data.append_bits("key1", <<"value2">>) 76 | /// |> form_data.set_bits("key1", <<"value3">>) 77 | /// ``` 78 | @external(javascript, "../../gleam_fetch_ffi.mjs", "setBitsFormData") 79 | pub fn set_bits(form_data: FormData, key: String, value: BitArray) -> FormData 80 | 81 | /// Remove a key and all its existing values. 82 | /// 83 | /// ```gleam 84 | /// form_data.new() 85 | /// |> form_data.append("key1", "value1") 86 | /// |> form_data.append_bits("key1", <<"value2">>) 87 | /// |> form_data.delete("key1") 88 | /// ``` 89 | @external(javascript, "../../gleam_fetch_ffi.mjs", "deleteFormData") 90 | pub fn delete(form_data: FormData, key: String) -> FormData 91 | 92 | /// Get String values associated with a key. If you're looking to also get 93 | /// binary values, take a look at [`get_bits`](#get_bits). 94 | /// 95 | /// ```gleam 96 | /// form_data.new() 97 | /// |> form_data.append("key1", "value1") 98 | /// |> form_data.append_bits("key1", <<"value2">>) 99 | /// |> form_data.get("key1") 100 | /// // -> ["value1"] 101 | /// ``` 102 | @external(javascript, "../../gleam_fetch_ffi.mjs", "getFormData") 103 | pub fn get(form_data: FormData, key: String) -> List(String) 104 | 105 | /// Get all values associated with a key, whether they're String or BitArray. 106 | /// Be careful, due to the nature of `FormData`, reading the blobs requires 107 | /// a `Promise`. 108 | /// 109 | /// ```gleam 110 | /// form_data.new() 111 | /// |> form_data.append("key1", "value1") 112 | /// |> form_data.append_bits("key1", <<"value2">>) 113 | /// |> form_data.get_bits("key1") 114 | /// // -> promise.resolve([<<"value1">>, <<"value2">>]) 115 | /// ``` 116 | @external(javascript, "../../gleam_fetch_ffi.mjs", "getBitsFormData") 117 | pub fn get_bits(form_data: FormData, key: String) -> Promise(List(BitArray)) 118 | 119 | /// Read if the key exists in the data. 120 | /// 121 | /// ```gleam 122 | /// form_data.new() 123 | /// |> form_data.append("key1", "value1") 124 | /// |> form_data.contains("key1") 125 | /// // -> True 126 | /// 127 | /// form_data.new() 128 | /// |> form_data.append("key1", "value1") 129 | /// |> form_data.contains("key2") 130 | /// // -> False 131 | /// ``` 132 | @external(javascript, "../../gleam_fetch_ffi.mjs", "hasFormData") 133 | pub fn contains(form_data: FormData, key: String) -> Bool 134 | 135 | /// Returns all keys present in the data. 136 | /// 137 | /// ```gleam 138 | /// form_data.new() 139 | /// |> form_data.append("key1", "value1") 140 | /// |> form_data.append("key2", "value2") 141 | /// |> form_data.keys 142 | /// // -> ["key1", "key2"] 143 | /// ``` 144 | @external(javascript, "../../gleam_fetch_ffi.mjs", "keysFormData") 145 | pub fn keys(form_data: FormData) -> List(String) 146 | -------------------------------------------------------------------------------- /src/gleam_fetch_ffi.mjs: -------------------------------------------------------------------------------- 1 | import { Ok, Error, List, toBitArray, toList } from "./gleam.mjs"; 2 | import { to_string as uri_to_string } from "../gleam_stdlib/gleam/uri.mjs"; 3 | import { method_to_string } from "../gleam_http/gleam/http.mjs"; 4 | import { to_uri } from "../gleam_http/gleam/http/request.mjs"; 5 | import { Response } from "../gleam_http/gleam/http/response.mjs"; 6 | import { 7 | NetworkError, 8 | InvalidJsonBody, 9 | UnableToReadBody, 10 | } from "../gleam_fetch/gleam/fetch.mjs"; 11 | 12 | export async function raw_send(request) { 13 | try { 14 | return new Ok(await fetch(request)); 15 | } catch (error) { 16 | return new Error(new NetworkError(error.toString())); 17 | } 18 | } 19 | 20 | export function from_fetch_response(response) { 21 | return new Response( 22 | response.status, 23 | List.fromArray([...response.headers]), 24 | response 25 | ); 26 | } 27 | 28 | function request_common(request) { 29 | let url = uri_to_string(to_uri(request)); 30 | let method = method_to_string(request.method).toUpperCase(); 31 | let options = { 32 | headers: make_headers(request.headers), 33 | method, 34 | }; 35 | return [url, options] 36 | } 37 | 38 | export function to_fetch_request(request) { 39 | let [url, options] = request_common(request) 40 | if (options.method !== "GET" && options.method !== "HEAD") options.body = request.body; 41 | return new globalThis.Request(url, options); 42 | } 43 | 44 | export function form_data_to_fetch_request(request) { 45 | let [url, options] = request_common(request) 46 | if (options.method !== "GET" && options.method !== "HEAD") options.body = request.body; 47 | // Remove `content-type`, because the browser will add the correct header by itself. 48 | delete options.headers['content-type'] 49 | return new globalThis.Request(url, options); 50 | } 51 | 52 | export function bitarray_request_to_fetch_request(request) { 53 | let [url, options] = request_common(request) 54 | if (options.method !== "GET" && options.method !== "HEAD") options.body = request.body.rawBuffer; 55 | return new globalThis.Request(url, options); 56 | } 57 | 58 | function make_headers(headersList) { 59 | let headers = new globalThis.Headers(); 60 | for (let [k, v] of headersList) headers.append(k.toLowerCase(), v); 61 | return headers; 62 | } 63 | 64 | export async function read_bytes_body(response) { 65 | let body; 66 | try { 67 | body = await response.body.arrayBuffer() 68 | } catch (error) { 69 | return new Error(new UnableToReadBody()); 70 | } 71 | return new Ok(response.withFields({ body: toBitArray(new Uint8Array(body)) })); 72 | } 73 | 74 | export async function read_text_body(response) { 75 | let body; 76 | try { 77 | body = await response.body.text(); 78 | } catch (error) { 79 | return new Error(new UnableToReadBody()); 80 | } 81 | return new Ok(response.withFields({ body })); 82 | } 83 | 84 | export async function read_json_body(response) { 85 | try { 86 | let body = await response.body.json(); 87 | return new Ok(response.withFields({ body })); 88 | } catch (error) { 89 | return new Error(new InvalidJsonBody()); 90 | } 91 | } 92 | 93 | // FormData functions. 94 | 95 | export function newFormData() { 96 | return new FormData() 97 | } 98 | 99 | function cloneFormData(formData) { 100 | const f = new FormData() 101 | for (const [key, value] of formData.entries()) f.append(key, value) 102 | return f 103 | } 104 | 105 | export function appendFormData(formData, key, value) { 106 | const f = cloneFormData(formData) 107 | f.append(key, value) 108 | return f 109 | } 110 | 111 | export function setFormData(formData, key, value) { 112 | const f = cloneFormData(formData) 113 | f.set(key, value) 114 | return f 115 | } 116 | 117 | export function appendBitsFormData(formData, key, value) { 118 | const f = cloneFormData(formData) 119 | f.append(key, new Blob([value.rawBuffer])) 120 | return f 121 | } 122 | 123 | export function setBitsFormData(formData, key, value) { 124 | const f = cloneFormData(formData) 125 | f.set(key, new Blob([value.rawBuffer])) 126 | return f 127 | } 128 | 129 | export function deleteFormData(formData, key) { 130 | const f = cloneFormData(formData) 131 | f.delete(key) 132 | return f 133 | } 134 | 135 | export function getFormData(formData, key) { 136 | const data = [...formData.getAll(key)] 137 | return toList(data.filter(value => typeof value === 'string')) 138 | } 139 | 140 | export async function getBitsFormData(formData, key) { 141 | const data = [...formData.getAll(key)] 142 | const encode = new TextEncoder() 143 | const blobs = data.map(async (value) => { 144 | if (typeof value === 'string') { 145 | const encoded = encode.encode(value) 146 | return toBitArray(encoded) 147 | } else { 148 | const buffer = await value.arrayBuffer() 149 | const bytes = new Uint8Array(buffer) 150 | return toBitArray(bytes) 151 | } 152 | }) 153 | const bytes = await Promise.all(blobs) 154 | return toList(bytes) 155 | } 156 | 157 | export function hasFormData(formData, key) { 158 | return formData.has(key) 159 | } 160 | 161 | export function keysFormData(formData) { 162 | const result = new Set() 163 | for (const key of formData.keys()) { 164 | result.add(key) 165 | } 166 | return toList([...result]) 167 | } 168 | -------------------------------------------------------------------------------- /test/gleam_fetch_test.gleam: -------------------------------------------------------------------------------- 1 | import gleam/fetch.{type FetchError} 2 | import gleam/fetch/form_data 3 | import gleam/http.{Get, Head, Options} 4 | import gleam/http/request 5 | import gleam/http/response.{type Response, Response} 6 | import gleam/javascript/promise 7 | import gleeunit 8 | import gleeunit/should 9 | 10 | pub fn main() { 11 | gleeunit.main() 12 | } 13 | 14 | pub fn request_test() { 15 | let req = 16 | request.new() 17 | |> request.set_method(Get) 18 | |> request.set_host("test-api.service.hmrc.gov.uk") 19 | |> request.set_path("/hello/world") 20 | |> request.prepend_header("accept", "application/vnd.hmrc.1.0+json") 21 | 22 | fetch.send(req) 23 | |> promise.try_await(fetch.read_bytes_body) 24 | |> promise.await(fn(resp: Result(Response(BitArray), FetchError)) { 25 | let assert Ok(resp) = resp 26 | let assert 200 = resp.status 27 | let assert Ok("application/json") = 28 | response.get_header(resp, "content-type") 29 | let assert << 30 | 123, 31 | 34, 32 | 109, 33 | 101, 34 | 115, 35 | 115, 36 | 97, 37 | 103, 38 | 101, 39 | 34, 40 | 58, 41 | 34, 42 | 72, 43 | 101, 44 | 108, 45 | 108, 46 | 111, 47 | 32, 48 | 87, 49 | 111, 50 | 114, 51 | 108, 52 | 100, 53 | 34, 54 | 125, 55 | >> = resp.body 56 | promise.resolve(Ok(Nil)) 57 | }) 58 | } 59 | 60 | pub fn text_request_test() { 61 | let req = 62 | request.new() 63 | |> request.set_method(Get) 64 | |> request.set_host("test-api.service.hmrc.gov.uk") 65 | |> request.set_path("/hello/world") 66 | |> request.prepend_header("accept", "application/vnd.hmrc.1.0+json") 67 | 68 | fetch.send(req) 69 | |> promise.try_await(fetch.read_text_body) 70 | |> promise.await(fn(resp: Result(Response(String), FetchError)) { 71 | let assert Ok(resp) = resp 72 | let assert 200 = resp.status 73 | let assert Ok("application/json") = 74 | response.get_header(resp, "content-type") 75 | let assert "{\"message\":\"Hello World\"}" = resp.body 76 | promise.resolve(Ok(Nil)) 77 | }) 78 | } 79 | 80 | pub fn json_request_test() { 81 | let req = 82 | request.new() 83 | |> request.set_method(Get) 84 | |> request.set_host("test-api.service.hmrc.gov.uk") 85 | |> request.set_path("/hello/world") 86 | |> request.prepend_header("accept", "application/vnd.hmrc.1.0+json") 87 | 88 | fetch.send(req) 89 | |> promise.try_await(fetch.read_json_body) 90 | |> promise.await(fn(resp) { 91 | let assert Ok(resp) = resp 92 | let assert 200 = resp.status 93 | let assert Ok("application/json") = 94 | response.get_header(resp, "content-type") 95 | // // TODO: make assertions about body 96 | promise.resolve(Ok(Nil)) 97 | }) 98 | } 99 | 100 | pub fn get_request_discards_body_test() { 101 | let req = 102 | request.new() 103 | |> request.set_method(Get) 104 | |> request.set_host("test-api.service.hmrc.gov.uk") 105 | |> request.set_path("/hello/world") 106 | |> request.set_body("This gets dropped") 107 | |> request.prepend_header("accept", "application/vnd.hmrc.1.0+json") 108 | 109 | fetch.send(req) 110 | |> promise.try_await(fetch.read_text_body) 111 | |> promise.await(fn(resp: Result(Response(String), FetchError)) { 112 | let assert Ok(resp) = resp 113 | let assert 200 = resp.status 114 | let assert Ok("application/json") = 115 | response.get_header(resp, "content-type") 116 | let assert "{\"message\":\"Hello World\"}" = resp.body 117 | promise.resolve(Ok(Nil)) 118 | }) 119 | } 120 | 121 | pub fn head_request_discards_body_test() { 122 | let request = 123 | request.new() 124 | |> request.set_method(Head) 125 | |> request.set_host("postman-echo.com") 126 | |> request.set_path("/get") 127 | |> request.set_body("This gets dropped") 128 | 129 | use response <- promise.try_await(fetch.send(request)) 130 | use response <- promise.await(fetch.read_text_body(response)) 131 | let assert Ok(resp) = response 132 | let assert 200 = resp.status 133 | let assert Ok("application/json; charset=utf-8") = 134 | response.get_header(resp, "content-type") 135 | let assert "" = resp.body 136 | promise.resolve(Ok(Nil)) 137 | } 138 | 139 | pub fn options_request_discards_body_test() { 140 | let req = 141 | request.new() 142 | |> request.set_method(Options) 143 | |> request.set_host("postman-echo.com") 144 | |> request.set_path("/get") 145 | |> request.set_body("This gets dropped") 146 | 147 | fetch.send(req) 148 | |> promise.try_await(fetch.read_text_body) 149 | |> promise.await(fn(resp) { 150 | let assert Ok(Response(status: 200, ..) as resp) = resp 151 | let assert Ok("text/html; charset=utf-8") = 152 | response.get_header(resp, "content-type") 153 | let assert "GET,HEAD,PUT,POST,DELETE,PATCH" = resp.body 154 | promise.resolve(Ok(Nil)) 155 | }) 156 | } 157 | 158 | pub fn form_data_keys_test() { 159 | let form_data = setup_form_data() 160 | form_data.keys(form_data) |> should.equal(["first-key", "second-key"]) 161 | form_data.contains(form_data, "first-key") |> should.equal(True) 162 | form_data.contains(form_data, "third-key") |> should.equal(False) 163 | let form_data = form_data.delete(form_data, "first-key") 164 | form_data.keys(form_data) |> should.equal(["second-key"]) 165 | } 166 | 167 | pub fn form_data_get_test() { 168 | let form_data = setup_form_data() 169 | form_data.get(form_data, "second-key") |> should.equal(["second-value"]) 170 | use content <- promise.await(form_data.get_bits(form_data, "second-key")) 171 | content 172 | |> should.equal([<<"second-value":utf8>>, <<"second-value-bits":utf8>>]) 173 | promise.resolve(Nil) 174 | } 175 | 176 | pub fn form_data_set_test() { 177 | let form_data = 178 | setup_form_data() 179 | |> form_data.set("first-key", "anything") 180 | |> form_data.set_bits("second-key", <<"anything":utf8>>) 181 | form_data.get(form_data, "first-key") |> should.equal(["anything"]) 182 | form_data.get(form_data, "second-key") |> should.equal([]) 183 | use fst_content <- promise.await(form_data.get_bits(form_data, "first-key")) 184 | use snd_content <- promise.await(form_data.get_bits(form_data, "second-key")) 185 | fst_content |> should.equal([<<"anything":utf8>>]) 186 | snd_content |> should.equal([<<"anything":utf8>>]) 187 | promise.resolve(Nil) 188 | } 189 | 190 | fn setup_form_data() { 191 | form_data.new() 192 | |> form_data.append("first-key", "first-value") 193 | |> form_data.append_bits("first-key", <<"first-value-bits":utf8>>) 194 | |> form_data.append("second-key", "second-value") 195 | |> form_data.append_bits("second-key", <<"second-value-bits":utf8>>) 196 | } 197 | -------------------------------------------------------------------------------- /test/polyfills.js: -------------------------------------------------------------------------------- 1 | import { default as fetch, Headers, Request, Response } from "node-fetch"; 2 | 3 | if (!globalThis.fetch) { 4 | globalThis.fetch = fetch; 5 | globalThis.Headers = Headers; 6 | globalThis.Request = Request; 7 | globalThis.Response = Response; 8 | } 9 | --------------------------------------------------------------------------------