├── packages.dhall ├── .gitignore ├── .tidyrc.json ├── .editorconfig ├── docs └── README.md ├── package.json ├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── bug-report.md │ └── change-request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── ci.yml ├── src ├── Affjax │ ├── StatusCode.purs │ ├── ResponseHeader.purs │ ├── RequestHeader.purs │ ├── RequestBody.purs │ └── ResponseFormat.purs ├── Affjax.js └── Affjax.purs ├── CONTRIBUTING.md ├── spago.dhall ├── .eslintrc.json ├── bower.json ├── README.md ├── CHANGELOG.md └── LICENSE /packages.dhall: -------------------------------------------------------------------------------- 1 | let upstream = 2 | https://raw.githubusercontent.com/purescript/package-sets/prepare-0.15/src/packages.dhall 3 | 4 | in upstream 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .* 2 | !.gitignore 3 | !.github 4 | !.editorconfig 5 | !.tidyrc.json 6 | !.eslintrc.json 7 | 8 | output 9 | generated-docs 10 | bower_components 11 | 12 | node_modules 13 | package-lock.json 14 | *.lock 15 | -------------------------------------------------------------------------------- /.tidyrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "importSort": "source", 3 | "importWrap": "source", 4 | "indent": 2, 5 | "operatorsFile": null, 6 | "ribbon": 1, 7 | "typeArrowPlacement": "first", 8 | "unicode": "never", 9 | "width": null 10 | } 11 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # Affjax Documentation 2 | 3 | This directory contains documentation for `affjax`. If you are interested in contributing new documentation, please read the [contributor guidelines](../CONTRIBUTING.md) and [What Nobody Tells You About Documentation](https://documentation.divio.com) for help getting started. 4 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "build": "eslint src && spago build --purs-args '--censor-lib --strict'" 5 | }, 6 | "devDependencies": { 7 | "body-parser": "^1.19.0", 8 | "eslint": "^7.10.0", 9 | "express": "^4.17.1", 10 | "purescript-psa": "^0.8.2", 11 | "xhr2": "^0.2.0" 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: PureScript Discourse 4 | url: https://discourse.purescript.org/ 5 | about: Ask and answer questions on the PureScript discussion forum. 6 | - name: PureScript Discord 7 | url: https://purescript.org/chat 8 | about: Ask and answer questions on the PureScript chat. 9 | -------------------------------------------------------------------------------- /src/Affjax/StatusCode.purs: -------------------------------------------------------------------------------- 1 | module Affjax.StatusCode where 2 | 3 | import Prelude 4 | import Data.Newtype (class Newtype) 5 | 6 | newtype StatusCode = StatusCode Int 7 | 8 | derive instance eqStatusCode :: Eq StatusCode 9 | derive instance ordStatusCode :: Ord StatusCode 10 | derive instance newtypeStatusCode :: Newtype StatusCode _ 11 | 12 | instance showStatusCode :: Show StatusCode where 13 | show (StatusCode code) = "(StatusCode " <> show code <> ")" 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Affjax 2 | 3 | Thanks for your interest in contributing to `affjax`! We welcome new contributions regardless of your level of experience or familiarity with PureScript. 4 | 5 | Every library in the Contributors organization shares a simple handbook that helps new contributors get started. With that in mind, please [read the short contributing guide on purescript-contrib/governance](https://github.com/purescript-contrib/governance/blob/main/contributing.md) before contributing to this library. 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Report an issue 4 | title: "" 5 | labels: bug 6 | assignees: "" 7 | --- 8 | 9 | **Describe the bug** 10 | A clear and concise description of the bug. 11 | 12 | **To Reproduce** 13 | A minimal code example (preferably a runnable example on [Try PureScript](https://try.purescript.org)!) or steps to reproduce the issue. 14 | 15 | **Expected behavior** 16 | A clear and concise description of what you expected to happen. 17 | 18 | **Additional context** 19 | Add any other context about the problem here. 20 | -------------------------------------------------------------------------------- /src/Affjax/ResponseHeader.purs: -------------------------------------------------------------------------------- 1 | module Affjax.ResponseHeader where 2 | 3 | import Prelude 4 | 5 | data ResponseHeader = ResponseHeader String String 6 | 7 | derive instance eqResponseHeader :: Eq ResponseHeader 8 | derive instance ordResponseHeader :: Ord ResponseHeader 9 | 10 | instance showResponseHeader :: Show ResponseHeader where 11 | show (ResponseHeader h v) = "(ResponseHeader " <> show h <> " " <> show v <> ")" 12 | 13 | name :: ResponseHeader -> String 14 | name (ResponseHeader h _) = h 15 | 16 | value :: ResponseHeader -> String 17 | value (ResponseHeader _ v) = v 18 | -------------------------------------------------------------------------------- /spago.dhall: -------------------------------------------------------------------------------- 1 | { name = "affjax" 2 | , dependencies = 3 | [ "aff" 4 | , "argonaut-core" 5 | , "arraybuffer-types" 6 | , "arrays" 7 | , "console" 8 | , "control" 9 | , "datetime" 10 | , "effect" 11 | , "either" 12 | , "exceptions" 13 | , "foldable-traversable" 14 | , "foreign" 15 | , "foreign-object" 16 | , "form-urlencoded" 17 | , "functions" 18 | , "http-methods" 19 | , "lists" 20 | , "maybe" 21 | , "media-types" 22 | , "newtype" 23 | , "nullable" 24 | , "prelude" 25 | , "transformers" 26 | , "web-dom" 27 | , "web-file" 28 | , "web-xhr" 29 | ] 30 | , packages = ./packages.dhall 31 | , sources = [ "src/**/*.purs" ] 32 | } 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/change-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Change request 3 | about: Propose an improvement to this library 4 | title: "" 5 | labels: "" 6 | assignees: "" 7 | --- 8 | 9 | **Is your change request related to a problem? Please describe.** 10 | A clear and concise description of the problem. 11 | 12 | Examples: 13 | 14 | - It's frustrating to have to [...] 15 | - I was looking for a function to [...] 16 | 17 | **Describe the solution you'd like** 18 | A clear and concise description of what a good solution to you looks like, including any solutions you've already considered. 19 | 20 | **Additional context** 21 | Add any other context about the change request here. 22 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | **Description of the change** 2 | Clearly and concisely describe the purpose of the pull request. If this PR relates to an existing issue or change proposal, please link to it. Include any other background context that would help reviewers understand the motivation for this PR. 3 | 4 | --- 5 | 6 | **Checklist:** 7 | 8 | - [ ] Added the change to the changelog's "Unreleased" section with a link to this PR and your username 9 | - [ ] Linked any existing issues or proposals that this pull request should close 10 | - [ ] Updated or added relevant documentation in the README and/or documentation directory 11 | - [ ] Added a test for the contribution (if applicable) 12 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint:recommended", 3 | "parserOptions": { "ecmaVersion": 6, "sourceType": "module" }, 4 | "rules": { 5 | "block-scoped-var": "error", 6 | "consistent-return": "error", 7 | "eqeqeq": "error", 8 | "guard-for-in": "error", 9 | "no-bitwise": "error", 10 | "no-caller": "error", 11 | "no-extra-parens": "off", 12 | "no-extend-native": "error", 13 | "no-loop-func": "error", 14 | "no-new": "error", 15 | "no-param-reassign": "error", 16 | "no-return-assign": "error", 17 | "no-sequences": "error", 18 | "no-unused-expressions": "error", 19 | "no-use-before-define": "error", 20 | "no-undef": "error", 21 | "no-eq-null": "error", 22 | "radix": ["error", "always"], 23 | "indent": ["error", 2, { "SwitchCase": 1 }], 24 | "quotes": ["error", "double"], 25 | "semi": ["error", "always"], 26 | "strict": ["error", "global"] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Affjax/RequestHeader.purs: -------------------------------------------------------------------------------- 1 | module Affjax.RequestHeader where 2 | 3 | import Prelude 4 | 5 | import Data.MediaType (MediaType) 6 | import Data.Newtype (unwrap) 7 | 8 | data RequestHeader 9 | = Accept MediaType 10 | | ContentType MediaType 11 | | RequestHeader String String 12 | 13 | derive instance eqRequestHeader :: Eq RequestHeader 14 | derive instance ordRequestHeader :: Ord RequestHeader 15 | 16 | instance showRequestHeader :: Show RequestHeader where 17 | show (Accept m) = "(Accept " <> show m <> ")" 18 | show (ContentType m) = "(ContentType " <> show m <> ")" 19 | show (RequestHeader h v) = "(RequestHeader " <> show h <> " " <> show v <> ")" 20 | 21 | name :: RequestHeader -> String 22 | name (Accept _) = "Accept" 23 | name (ContentType _) = "Content-Type" 24 | name (RequestHeader h _) = h 25 | 26 | value :: RequestHeader -> String 27 | value (Accept m) = unwrap m 28 | value (ContentType m) = unwrap m 29 | value (RequestHeader _ v) = v 30 | -------------------------------------------------------------------------------- /src/Affjax/RequestBody.purs: -------------------------------------------------------------------------------- 1 | module Affjax.RequestBody where 2 | 3 | import Data.Argonaut.Core (Json) 4 | import Data.ArrayBuffer.Types as A 5 | import Data.FormURLEncoded (FormURLEncoded) 6 | import Data.Maybe (Maybe(..)) 7 | import Data.MediaType (MediaType) 8 | import Data.MediaType.Common (applicationJSON, applicationFormURLEncoded) 9 | import Web.DOM.Document (Document) 10 | import Web.File.Blob (Blob) 11 | import Web.XHR.FormData (FormData) 12 | 13 | -- | Represents data for an HTTP request that will be included in the request 14 | -- | body. 15 | data RequestBody 16 | = ArrayView (forall r. (forall a. A.ArrayView a -> r) -> r) 17 | | Blob Blob 18 | | Document Document 19 | | String String 20 | | FormData FormData 21 | | FormURLEncoded FormURLEncoded 22 | | Json Json 23 | 24 | arrayView :: forall a. A.ArrayView a -> RequestBody 25 | arrayView av = ArrayView \f -> f av 26 | 27 | blob :: Blob -> RequestBody 28 | blob = Blob 29 | 30 | document :: Document -> RequestBody 31 | document = Document 32 | 33 | string :: String -> RequestBody 34 | string = String 35 | 36 | formData :: FormData -> RequestBody 37 | formData = FormData 38 | 39 | formURLEncoded :: FormURLEncoded -> RequestBody 40 | formURLEncoded = FormURLEncoded 41 | 42 | json :: Json -> RequestBody 43 | json = Json 44 | 45 | toMediaType :: RequestBody -> Maybe MediaType 46 | toMediaType = case _ of 47 | FormURLEncoded _ -> Just applicationFormURLEncoded 48 | Json _ -> Just applicationJSON 49 | _ -> Nothing 50 | -------------------------------------------------------------------------------- /src/Affjax/ResponseFormat.purs: -------------------------------------------------------------------------------- 1 | module Affjax.ResponseFormat where 2 | 3 | import Prelude 4 | 5 | import Data.Argonaut.Core (Json) 6 | import Data.ArrayBuffer.Types (ArrayBuffer) 7 | import Data.Maybe (Maybe(..)) 8 | import Data.MediaType (MediaType) 9 | import Data.MediaType.Common (applicationJSON) 10 | import Web.DOM.Document (Document) 11 | import Web.File.Blob (Blob) 12 | 13 | -- | Used to represent how a HTTP response body should be interpreted. 14 | data ResponseFormat a 15 | = ArrayBuffer (forall f. f ArrayBuffer -> f a) 16 | | Blob (forall f. f Blob -> f a) 17 | | Document (forall f. f Document -> f a) 18 | | Json (forall f. f Json -> f a) 19 | | String (forall f. f String -> f a) 20 | | Ignore (forall f. f Unit -> f a) 21 | 22 | arrayBuffer :: ResponseFormat ArrayBuffer 23 | arrayBuffer = ArrayBuffer identity 24 | 25 | blob :: ResponseFormat Blob 26 | blob = Blob identity 27 | 28 | document :: ResponseFormat Document 29 | document = Document identity 30 | 31 | json :: ResponseFormat Json 32 | json = Json identity 33 | 34 | string :: ResponseFormat String 35 | string = String identity 36 | 37 | ignore :: ResponseFormat Unit 38 | ignore = Ignore identity 39 | 40 | -- | Converts a `Response a` into a string representation of the response type 41 | -- | that it represents. 42 | toResponseType :: forall a. ResponseFormat a -> String 43 | toResponseType = 44 | case _ of 45 | ArrayBuffer _ -> "arraybuffer" 46 | Blob _ -> "blob" 47 | Document _ -> "document" 48 | Json _ -> "text" -- IE doesn't support "json" ResponseFormat 49 | String _ -> "text" 50 | Ignore _ -> "" 51 | 52 | toMediaType :: forall a. ResponseFormat a -> Maybe MediaType 53 | toMediaType = 54 | case _ of 55 | Json _ -> Just applicationJSON 56 | _ -> Nothing 57 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "purescript-affjax", 3 | "homepage": "https://github.com/slamdata/purescript-affjax", 4 | "description": "An asynchronous AJAX library built using Aff.", 5 | "keywords": [ 6 | "purescript", 7 | "ajax" 8 | ], 9 | "license": "Apache-2.0", 10 | "repository": { 11 | "type": "git", 12 | "url": "https://github.com/purescript-contrib/purescript-affjax.git" 13 | }, 14 | "ignore": [ 15 | "**/.*", 16 | "bower_components", 17 | "node_modules", 18 | "output", 19 | "test", 20 | "tmp", 21 | "bower.json", 22 | "gulpfile.js", 23 | "package.json" 24 | ], 25 | "dependencies": { 26 | "purescript-aff": "^7.0.0", 27 | "purescript-argonaut-core": "^7.0.0", 28 | "purescript-arraybuffer-types": "^3.0.2", 29 | "purescript-arrays": "^7.0.0", 30 | "purescript-console": "^6.0.0", 31 | "purescript-control": "^6.0.0", 32 | "purescript-datetime": "^6.0.0", 33 | "purescript-effect": "^4.0.0", 34 | "purescript-either": "^6.0.0", 35 | "purescript-exceptions": "^6.0.0", 36 | "purescript-foldable-traversable": "^6.0.0", 37 | "purescript-foreign": "^7.0.0", 38 | "purescript-foreign-object": "^4.0.0", 39 | "purescript-form-urlencoded": "^7.0.0", 40 | "purescript-functions": "^6.0.0", 41 | "purescript-http-methods": "^6.0.0", 42 | "purescript-lists": "^7.0.0", 43 | "purescript-maybe": "^6.0.0", 44 | "purescript-media-types": "^6.0.0", 45 | "purescript-newtype": "^5.0.0", 46 | "purescript-nullable": "^6.0.0", 47 | "purescript-prelude": "^6.0.0", 48 | "purescript-transformers": "^6.0.0", 49 | "purescript-web-dom": "^6.0.0", 50 | "purescript-web-file": "^4.0.0", 51 | "purescript-web-xhr": "^5.0.0" 52 | }, 53 | "devDependencies": { 54 | "purescript-psci-support": "^6.0.0" 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | 16 | - name: Set up PureScript toolchain 17 | uses: purescript-contrib/setup-purescript@main 18 | with: 19 | purescript: "unstable" 20 | purs-tidy: "latest" 21 | 22 | - name: Cache PureScript dependencies 23 | uses: actions/cache@v2 24 | with: 25 | key: ${{ runner.os }}-spago-${{ hashFiles('**/*.dhall') }} 26 | path: | 27 | .spago 28 | output 29 | 30 | - name: Set up Node toolchain 31 | uses: actions/setup-node@v2 32 | with: 33 | node-version: "14.x" 34 | 35 | - name: Cache NPM dependencies 36 | uses: actions/cache@v2 37 | env: 38 | cache-name: cache-node-modules 39 | with: 40 | path: ~/.npm 41 | key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package.json') }} 42 | restore-keys: | 43 | ${{ runner.os }}-build-${{ env.cache-name }}- 44 | ${{ runner.os }}-build- 45 | ${{ runner.os }}- 46 | 47 | - name: Install NPM dependencies 48 | run: npm install 49 | 50 | - name: Build the project 51 | run: npm run build 52 | 53 | - name: Run tests 54 | run: npm run test 55 | 56 | - name: Check formatting 57 | run: purs-tidy check src test 58 | 59 | - name: Verify Bower & Pulp 60 | run: | 61 | npm install bower pulp@16.0.0-0 62 | npx bower install 63 | npx pulp build -- --censor-lib --strict 64 | if [ -d "test" ]; then 65 | npx pulp test 66 | fi 67 | -------------------------------------------------------------------------------- /src/Affjax.js: -------------------------------------------------------------------------------- 1 | export function _ajax(platformSpecificDriver, timeoutErrorMessageIdent, requestFailedMessageIdent, mkHeader, options) { 2 | return function (errback, callback) { 3 | var xhr = platformSpecificDriver.newXHR(); 4 | var fixedUrl = platformSpecificDriver.fixupUrl(options.url, xhr); 5 | xhr.open(options.method || "GET", fixedUrl, true, options.username, options.password); 6 | if (options.headers) { 7 | try { 8 | // eslint-disable-next-line no-eq-null,eqeqeq 9 | for (var i = 0, header; (header = options.headers[i]) != null; i++) { 10 | xhr.setRequestHeader(header.field, header.value); 11 | } 12 | } catch (e) { 13 | errback(e); 14 | } 15 | } 16 | var onerror = function (msgIdent) { 17 | return function () { 18 | errback(new Error(msgIdent)); 19 | }; 20 | }; 21 | xhr.onerror = onerror(requestFailedMessageIdent); 22 | xhr.ontimeout = onerror(timeoutErrorMessageIdent); 23 | xhr.onload = function () { 24 | callback({ 25 | status: xhr.status, 26 | statusText: xhr.statusText, 27 | headers: xhr.getAllResponseHeaders().split("\r\n") 28 | .filter(function (header) { 29 | return header.length > 0; 30 | }) 31 | .map(function (header) { 32 | var i = header.indexOf(":"); 33 | return mkHeader(header.substring(0, i))(header.substring(i + 2)); 34 | }), 35 | body: xhr.response 36 | }); 37 | }; 38 | xhr.responseType = options.responseType; 39 | xhr.withCredentials = options.withCredentials; 40 | xhr.timeout = options.timeout; 41 | xhr.send(options.content); 42 | 43 | return function (error, cancelErrback, cancelCallback) { 44 | try { 45 | xhr.abort(); 46 | } catch (e) { 47 | return cancelErrback(e); 48 | } 49 | return cancelCallback(); 50 | }; 51 | }; 52 | } 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Affjax 2 | 3 | [![CI](https://github.com/purescript-contrib/purescript-affjax/workflows/CI/badge.svg?branch=main)](https://github.com/purescript-contrib/purescript-affjax/actions?query=workflow%3ACI+branch%3Amain) 4 | [![Release](https://img.shields.io/github/release/purescript-contrib/purescript-affjax.svg)](https://github.com/purescript-contrib/purescript-affjax/releases) 5 | [![Pursuit](https://pursuit.purescript.org/packages/purescript-affjax/badge)](https://pursuit.purescript.org/packages/purescript-affjax) 6 | [![Maintainer: garyb](https://img.shields.io/badge/maintainer-garyb-teal.svg)](https://github.com/garyb) 7 | 8 | A library taking advantage of [`aff`](https://github.com/purescript-contrib/purescript-aff) to enable pain-free asynchronous AJAX requests and response handling. 9 | 10 | This library provides types and common functionality that work across environments (e.g. Node, browser), but **it does not work out-of-box**. Rather, use the environment-specific library instead: 11 | - Browser environment: [`purescript-affjax-web`](https://github.com/purescript-contrib/purescript-affjax-web) 12 | - Node environment: [`purescript-affjax-node`](https://github.com/purescript-contrib/purescript-affjax-node) 13 | 14 | ## Documentation 15 | 16 | `affjax` documentation is stored in a few places: 17 | 18 | 1. Module documentation is [published on Pursuit](https://pursuit.purescript.org/packages/purescript-affjax). 19 | 2. Written documentation is kept in the [docs directory](./docs). 20 | 3. Usage examples can be found in [the test suite](./test). 21 | 22 | If you get stuck, there are several ways to get help: 23 | 24 | - [Open an issue](https://github.com/purescript-contrib/purescript-affjax/issues) if you have encountered a bug or problem. 25 | - Ask general questions on the [PureScript Discourse](https://discourse.purescript.org) forum or the [PureScript Discord](https://purescript.org/chat) chat. 26 | 27 | ## Contributing 28 | 29 | You can contribute to `affjax` in several ways: 30 | 31 | 1. If you encounter a problem or have a question, please [open an issue](https://github.com/purescript-contrib/purescript-affjax/issues). We'll do our best to work with you to resolve or answer it. 32 | 33 | 2. If you would like to contribute code, tests, or documentation, please [read the contributor guide](./CONTRIBUTING.md). It's a short, helpful introduction to contributing to this library, including development instructions. 34 | 35 | 3. If you have written a library, tutorial, guide, or other resource based on this package, please share it on the [PureScript Discourse](https://discourse.purescript.org)! Writing libraries and learning resources are a great way to help this library succeed. 36 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | Notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 4 | 5 | ## [Unreleased] 6 | 7 | Breaking changes: 8 | 9 | New features: 10 | 11 | Bugfixes: 12 | 13 | Other improvements: 14 | 15 | ## [v13.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v13.0.0) - 2022-04-28 16 | 17 | Breaking changes: 18 | - Update project and deps to PureScript v0.15.0 (#171 by @JordanMartinez) 19 | - Update all request functions to take a driver arg (#171 by @JordanMartinez) 20 | 21 | Affjax works on the Node.js and browser environments by relying on a `require` 22 | statement within a function. Depending on the environment detected, 23 | either `XHR` or `XmlHttpRequest` is used. Since ES modules do not allow 24 | one to call `import` within a function in a _synchronous_ way, 25 | we cannot continue to use this approach. 26 | 27 | Rather, all request-related functions (e.g. `request`, `get`, etc.) now take 28 | as their first argument an `AffjaxDriver` value. Different environments 29 | will pass in their implementation for that driver and re-export 30 | the functionality defined in `affjax`. 31 | 32 | To fix your code, depend on the corresponding library below and update the imported 33 | module from `Affjax` to `Affjax.Node`/`Affjax.Web`: 34 | - If on Node.js, use [`purescript-affjax-node`](https://github.com/purescript-contrib/purescript-affjax-node/). 35 | - If on the brower, use [`purescript-affjax-web`](https://github.com/purescript-contrib/purescript-affjax-web/). 36 | 37 | New features: 38 | 39 | Bugfixes: 40 | 41 | Other improvements: 42 | - Added `purs-tidy` formatter (#167 by @thomashoneyman) 43 | 44 | ## [v12.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v12.0.0) - 2021-02-26 45 | 46 | Breaking changes: 47 | - Added support for PureScript 0.14 and dropped support for all previous versions (#158) 48 | - `XHRError Exn.Error` was removed and split to `TimeoutError`, `RequestFailedError`, and `XHROtherError Exn.Error` (#155, @srghma) 49 | 50 | New features: 51 | 52 | Bugfixes: 53 | 54 | Other improvements: 55 | - `XMLDocument` and `HTMLDocument` are now understood as `Document` responses (#157) 56 | - Changed default branch to `main` from `master` 57 | - Updated to comply with Contributors library guidelines by adding new issue and pull request templates, updating documentation, and migrating to Spago for local development and CI (#153) 58 | 59 | ## [v11.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v11.0.0) - 2020-09-06 60 | 61 | - Added support for the `timeout` option in `Request` (#151) 62 | 63 | ## [v10.1.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v10.1.0) - 2020-06-07 64 | 65 | - Added `Newtype` instance for `StatusCode` (@ford-prefect) 66 | 67 | ## [v10.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v10.0.0) - 2019-11-03 68 | 69 | - Updated for latest `purescript-form-urlencoded`. 70 | - Some helper functions were combined to accept `Maybe RequestBody` rather than having two variations of each. 71 | - All request functions now return `Either Error _`; the `Aff` error channel is no longer used to capture errors from the `XHR` object, and the provided `Error` type captures the various possible error cases that can occur. 72 | - `retry` was removed. 73 | 74 | ## [v9.0.1](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v9.0.1) - 2019-09-05 75 | 76 | - Ensured version mismatch with `purescript-form-urlencoded` does not compile, potentially resulting in runtime errors (spotted by @menelaos) 77 | - Don't override `nodejsBaseUrl` already set in `xhr2` on node (@paul-rouse) 78 | 79 | ## [v9.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v9.0.0) - 2019-03-11 80 | 81 | - Updated for latest `purescript-argonaut-core` 82 | 83 | ## [v8.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v8.0.0) - 2019-02-23 84 | 85 | - Updated `purescript-web-xhr` dependency 86 | - Renamed functions in the `RequestHeader` / `ResponseHeader` modules to no longer prefix values with the module name 87 | 88 | ## [v7.0.2](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v7.0.2) - 2019-02-09 89 | 90 | - XHR timeouts are now caught and raised through `Aff`'s error channel (@acple) 91 | 92 | ## [v7.0.1](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v7.0.1) - 2019-01-31 93 | 94 | - Fixed an incorrect `request` example in the doc comments (@jhrcek) 95 | 96 | ## [v7.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v7.0.0) - 2018-08-12 97 | 98 | Lots of things were renamed in this release to better match their current functionality: 99 | 100 | - The `affjax` function is now `request` 101 | - The `AffjaxRequest` record is now `Request` 102 | - The `AffjaxResponse` record is now `Response` 103 | - The `response` field of `Response` is now `body` 104 | - The `Request` type is now `RequestBody` 105 | - The `Response` type is now `ResponseFormat` 106 | - The `Request` record now has a `responseFormat` field, rather than it being a separate argument to `request` 107 | 108 | (Most of the new names by @paldepind). 109 | 110 | Additionally, errors that occur during decoding a response no longer cause an entire request to fail. The `body` value is now `Either ResponseFormatError a`, so that other details about the response can still be inspected (status code, for example), even if the response body fails to decode. The `ResponseFormatError` value also carries the response body as a `Foreign` value, in case there is some further special handling that can be performed externally. 111 | 112 | ## [v6.0.1](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v6.0.1) - 2018-08-05 113 | 114 | - Improved documentation (@paldepind) 115 | 116 | ## [v6.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v6.0.0) - 2018-05-27 117 | 118 | - Updated for PureScript 0.12 119 | - `Requestable` and `Respondable` classes have now been removed in favour of using explicit values 120 | - `statusText` is now available in responses (@danbornside) 121 | - The `Aff` canceller was fixed (@doolse) 122 | 123 | ## [v5.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v5.0.0) - 2017-09-14 124 | 125 | - Updated for `purescript-aff` v4.0.0. 126 | 127 | ## [v4.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v4.0.0) - 2017-04-10 128 | 129 | - Updated for PureScript 0.11 (@NasalMusician) 130 | 131 | ## [v3.0.2](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v3.0.2) - 2016-12-01 132 | 133 | - Tweaked JS to enable `affjax` to work in Electron apps (@aratama) 134 | 135 | ## [v3.0.1](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v3.0.1) - 2016-11-15 136 | 137 | - Fixed shadowed name warning 138 | 139 | ## [v3.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v3.0.0) - 2016-11-01 140 | 141 | - Updated dependencies for PureScript 0.10 142 | 143 | ## [v2.0.1](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v2.0.1) - 2016-09-11 144 | 145 | - Fixed a bug in splitting headers #81 (@jasonzoladz) 146 | 147 | ## [v2.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v2.0.0) - 2016-07-31 148 | 149 | - Updated dependencies 150 | 151 | ## [v1.2.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v1.2.0) - 2016-07-28 152 | 153 | - Added convenience functions for `PATCH` operations (@clayrat) 154 | 155 | ## [v1.0.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v1.0.0) - 2016-06-18 156 | 157 | - Updated for the 1.0 core libraries and PureScript 0.9.x. 158 | 159 | ## [v0.13.2](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.13.2) - 2016-05-12 160 | 161 | - Updated for Pursuit publishing 162 | 163 | ## [v0.13.1](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.13.1) - 2016-04-10 164 | 165 | - Set `purescript-dom` lower bound to ensure compatibility with psc 0.8.4 (@damncabbage) 166 | 167 | ## [v0.13.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.13.0) - 2016-03-12 168 | 169 | - Updated `purescript-aff` dependency 170 | - Now uses types from `purescript-http-methods` and `purescript-media-types` 171 | 172 | ## [v0.12.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.12.0) - 2016-02-26 173 | 174 | - Added `withCredentials` option (@brendanhay) 175 | 176 | ## [v0.11.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.11.0) - 2016-02-22 177 | 178 | - Updated `purescript-aff` dependency 179 | 180 | ## [v0.10.4](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.10.4) - 2016-02-12 181 | 182 | - Added `Requestable` instance for `FormURLEncoded` (@zudov) 183 | 184 | ## [v0.10.2](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.10.2) - 2016-01-30 185 | 186 | - Errors rasied by `setRequestHeader` are now caught #58 (@codedmart) 187 | 188 | ## [v0.10.1](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.10.1) - 2016-01-07 189 | 190 | - Fixed handling of JSON-value responses #54, #55 191 | 192 | ## [v0.10.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.10.0) - 2015-11-20 193 | 194 | - Added `Json` instance for `Requestable` and `Respondable` 195 | - `Requestable` and `Respondable` now include an optional `MimeType` to use as the default `Content-Type` or `Accept` header. 196 | 197 | ## [v0.9.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.9.0) - 2015-10-16 198 | 199 | - Node support is now provided by `xhr2` rather than `xmlhttprequest` (fixes #44) (@stkb) 200 | 201 | ## [v0.8.1](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.8.1) - 2015-10-10 202 | 203 | - Added `Respondable ArrayBuffer` instance (@quephird) 204 | 205 | ## [v0.8.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.8.0) - 2015-09-23 206 | 207 | - Updated dependencies 208 | 209 | ## [v0.7.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.7.0) - 2015-08-31 210 | 211 | - Updated dependencies and fixed warnings for PureScript 0.7.4 212 | 213 | ## [v0.5.1](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.5.1) - 2015-08-05 214 | 215 | - Added support for node via npm package 'xmlhttprequest' (@hdgarrood) 216 | 217 | ## [v0.4.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.4.0) - 2015-07-07 218 | 219 | - Updated for PureScript 0.7 (@qxjit) 220 | 221 | ## [v0.3.2](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.3.2) - 2015-06-08 222 | 223 | - A better fix for `JSONResponse` use in `Respondable` - this fix preserves the original behaviour in custom `Respondable` instances. 224 | 225 | ## [v0.3.1](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.3.1) - 2015-06-08 226 | 227 | - Fixed an issue with the `Respondable Foreign` instance - IE does not support automatic reading of JSON with `responseType = "json"`. 228 | 229 | ## [v0.3.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.3.0) - 2015-05-18 230 | 231 | - Bumped `purescript-integers` dependency 232 | 233 | ## [v0.2.1](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.2.1) - 2015-04-23 234 | 235 | - `ResponseType` constructors are now exported so that custom `Respondable` instances can be declared. 236 | 237 | ## [v0.2.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.2.0) - 2015-04-20 238 | 239 | - Eliminates use of Proxy for a simpler implementation of Requestable. 240 | 241 | ## [v0.1.0](https://github.com/purescript-contrib/purescript-affjax/releases/tag/v0.1.0) - 2015-04-20 242 | 243 | - This is the first beta release of Affjax, a library designed to expose AJAX through Aff. 244 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/Affjax.purs: -------------------------------------------------------------------------------- 1 | -- | Note: this module is not intended to be used by end-users. 2 | -- | Rather, use the environment-specific library instead: 3 | -- | - [`purescript-affjax-node`](https://github.com/purescript-contrib/purescript-affjax-node) 4 | -- | - [`purescript-affjax-web`](https://github.com/purescript-contrib/purescript-affjax-web) 5 | -- | 6 | -- | You should use this module if you are writing a driver for a specific environment. 7 | -- | See this module's source code for more details. 8 | -- If you want to write a driver for an environment, see the comments 9 | -- for the `AffjaxDriver` type and look at the `node` and `web` libraries 10 | -- (linked above) as examples. 11 | module Affjax 12 | ( Request 13 | , defaultRequest 14 | , Response 15 | , Error(..) 16 | , printError 17 | , URL 18 | , AffjaxDriver 19 | , request 20 | , get 21 | , post 22 | , post_ 23 | , put 24 | , put_ 25 | , delete 26 | , delete_ 27 | , patch 28 | , patch_ 29 | ) where 30 | 31 | import Prelude 32 | 33 | import Affjax.RequestBody as RequestBody 34 | import Affjax.RequestHeader (RequestHeader(..)) 35 | import Affjax.RequestHeader as RequestHeader 36 | import Affjax.ResponseFormat as ResponseFormat 37 | import Affjax.ResponseHeader (ResponseHeader(..)) 38 | import Affjax.StatusCode (StatusCode) 39 | import Control.Alt ((<|>)) 40 | import Control.Monad.Except (Except, runExcept) 41 | import Data.Argonaut.Core (Json) 42 | import Data.Argonaut.Core as J 43 | import Data.Argonaut.Parser (jsonParser) 44 | import Data.Array as Arr 45 | import Data.ArrayBuffer.Types (ArrayView) 46 | import Data.Either (Either(..), either, note) 47 | import Data.Foldable (any) 48 | import Data.FormURLEncoded as FormURLEncoded 49 | import Data.Function (on) 50 | import Data.Function.Uncurried (Fn5, runFn5) 51 | import Data.HTTP.Method (Method(..), CustomMethod) 52 | import Data.HTTP.Method as Method 53 | import Data.List.NonEmpty as NEL 54 | import Data.Maybe (Maybe(..), fromMaybe) 55 | import Data.Nullable (Nullable, toNullable) 56 | import Data.Time.Duration (Milliseconds(..)) 57 | import Effect.Aff (Aff, try) 58 | import Effect.Aff.Compat as AC 59 | import Effect.Exception as Exn 60 | import Foreign (Foreign, ForeignError(..), fail, renderForeignError, unsafeReadTagged, unsafeToForeign) 61 | import Web.DOM (Document) 62 | import Web.File.Blob (Blob) 63 | import Web.XHR.FormData (FormData) 64 | 65 | -- | A record that contains all the information to perform an HTTP request. 66 | -- | Instead of constructing the record from scratch it is often easier to build 67 | -- | one based on `defaultRequest`. 68 | type Request a = 69 | { method :: Either Method CustomMethod 70 | , url :: URL 71 | , headers :: Array RequestHeader 72 | , content :: Maybe RequestBody.RequestBody 73 | , username :: Maybe String 74 | , password :: Maybe String 75 | , withCredentials :: Boolean 76 | , responseFormat :: ResponseFormat.ResponseFormat a 77 | , timeout :: Maybe Milliseconds 78 | } 79 | 80 | -- | A record of the type `Request` that has all fields set to default 81 | -- | values. This record can be used as the foundation for constructing 82 | -- | custom requests. 83 | -- | 84 | -- | As an example: 85 | -- | 86 | -- | ```purescript 87 | -- | defaultRequest { url = "/api/user", method = Left POST } 88 | -- | ``` 89 | -- | 90 | -- | Would represents a POST request to the URL `/api/user`. 91 | defaultRequest :: Request Unit 92 | defaultRequest = 93 | { method: Left GET 94 | , url: "/" 95 | , headers: [] 96 | , content: Nothing 97 | , username: Nothing 98 | , password: Nothing 99 | , withCredentials: false 100 | , responseFormat: ResponseFormat.ignore 101 | , timeout: Nothing 102 | } 103 | 104 | -- | The possible errors that can occur when making an Affjax request. 105 | data Error 106 | = RequestContentError String 107 | | ResponseBodyError ForeignError (Response Foreign) 108 | | TimeoutError 109 | | RequestFailedError 110 | | XHROtherError Exn.Error 111 | 112 | printError :: Error -> String 113 | printError = case _ of 114 | RequestContentError err -> 115 | "There was a problem with the request content: " <> err 116 | ResponseBodyError err _ -> 117 | "There was a problem with the response body: " <> renderForeignError err 118 | TimeoutError -> 119 | "There was a problem making the request: timeout" 120 | RequestFailedError -> 121 | "There was a problem making the request: request failed" 122 | XHROtherError err -> 123 | "There was a problem making the request: " <> Exn.message err 124 | 125 | -- | The type of records that represents a received HTTP response. 126 | type Response a = 127 | { status :: StatusCode 128 | , statusText :: String 129 | , headers :: Array ResponseHeader 130 | , body :: a 131 | } 132 | 133 | -- | Type alias for URL strings to aid readability of types. 134 | type URL = String 135 | 136 | -- | Makes a `GET` request to the specified URL. 137 | get :: forall a. AffjaxDriver -> ResponseFormat.ResponseFormat a -> URL -> Aff (Either Error (Response a)) 138 | get driver rf u = request driver (defaultRequest { url = u, responseFormat = rf }) 139 | 140 | -- | Makes a `POST` request to the specified URL with the option to send data. 141 | post :: forall a. AffjaxDriver -> ResponseFormat.ResponseFormat a -> URL -> Maybe RequestBody.RequestBody -> Aff (Either Error (Response a)) 142 | post driver rf u c = request driver (defaultRequest { method = Left POST, url = u, content = c, responseFormat = rf }) 143 | 144 | -- | Makes a `POST` request to the specified URL with the option to send data 145 | -- | and ignores the response body. 146 | post_ :: AffjaxDriver -> URL -> Maybe RequestBody.RequestBody -> Aff (Either Error Unit) 147 | post_ driver url = map void <<< post driver ResponseFormat.ignore url 148 | 149 | -- | Makes a `PUT` request to the specified URL with the option to send data. 150 | put :: forall a. AffjaxDriver -> ResponseFormat.ResponseFormat a -> URL -> Maybe RequestBody.RequestBody -> Aff (Either Error (Response a)) 151 | put driver rf u c = request driver (defaultRequest { method = Left PUT, url = u, content = c, responseFormat = rf }) 152 | 153 | -- | Makes a `PUT` request to the specified URL with the option to send data 154 | -- | and ignores the response body. 155 | put_ :: AffjaxDriver -> URL -> Maybe RequestBody.RequestBody -> Aff (Either Error Unit) 156 | put_ driver url = map void <<< put driver ResponseFormat.ignore url 157 | 158 | -- | Makes a `DELETE` request to the specified URL. 159 | delete :: forall a. AffjaxDriver -> ResponseFormat.ResponseFormat a -> URL -> Aff (Either Error (Response a)) 160 | delete driver rf u = request driver (defaultRequest { method = Left DELETE, url = u, responseFormat = rf }) 161 | 162 | -- | Makes a `DELETE` request to the specified URL and ignores the response 163 | -- | body. 164 | delete_ :: AffjaxDriver -> URL -> Aff (Either Error Unit) 165 | delete_ driver = map void <<< delete driver ResponseFormat.ignore 166 | 167 | -- | Makes a `PATCH` request to the specified URL with the option to send data. 168 | patch :: forall a. AffjaxDriver -> ResponseFormat.ResponseFormat a -> URL -> RequestBody.RequestBody -> Aff (Either Error (Response a)) 169 | patch driver rf u c = request driver (defaultRequest { method = Left PATCH, url = u, content = Just c, responseFormat = rf }) 170 | 171 | -- | Makes a `PATCH` request to the specified URL with the option to send data 172 | -- | and ignores the response body. 173 | patch_ :: AffjaxDriver -> URL -> RequestBody.RequestBody -> Aff (Either Error Unit) 174 | patch_ driver url = map void <<< patch driver ResponseFormat.ignore url 175 | 176 | -- | Makes an HTTP request. 177 | -- | 178 | -- | The example below performs a `GET` request to the URL `/resource` and 179 | -- | interprets the response body as JSON. 180 | -- | 181 | -- | ```purescript 182 | -- | import Affjax.ResponseFormat (json) 183 | -- | ... 184 | -- | request (defaultRequest { url = "/resource", method = Left GET, responseFormat = json}) 185 | -- | ``` 186 | -- | 187 | -- | For common cases helper functions can often be used instead of `request` . 188 | -- | For instance, the above example is equivalent to the following. 189 | -- | 190 | -- | ```purescript 191 | -- | get json "/resource" 192 | -- | ``` 193 | request :: forall a. AffjaxDriver -> Request a -> Aff (Either Error (Response a)) 194 | request driver req = 195 | case req.content of 196 | Nothing -> 197 | send (toNullable Nothing) 198 | Just content -> 199 | case extractContent content of 200 | Right c -> 201 | send (toNullable (Just c)) 202 | Left err -> 203 | pure $ Left (RequestContentError err) 204 | where 205 | send :: Nullable Foreign -> Aff (Either Error (Response a)) 206 | send content = 207 | try (AC.fromEffectFnAff (runFn5 _ajax driver timeoutErrorMessageIdent requestFailedMessageIdent ResponseHeader (ajaxRequest content))) <#> case _ of 208 | Right res -> 209 | case runExcept (fromResponse res.body) of 210 | Left err -> Left (ResponseBodyError (NEL.head err) res) 211 | Right body -> Right (res { body = body }) 212 | Left err -> Left do 213 | let message = Exn.message err 214 | if message == timeoutErrorMessageIdent then 215 | TimeoutError 216 | else if message == requestFailedMessageIdent then 217 | RequestFailedError 218 | else 219 | XHROtherError err 220 | 221 | ajaxRequest :: Nullable Foreign -> AjaxRequest a 222 | ajaxRequest = 223 | { method: Method.print req.method 224 | , url: req.url 225 | , headers: (\h -> { field: RequestHeader.name h, value: RequestHeader.value h }) <$> headers req.content 226 | , content: _ 227 | , responseType: ResponseFormat.toResponseType req.responseFormat 228 | , username: toNullable req.username 229 | , password: toNullable req.password 230 | , withCredentials: req.withCredentials 231 | , timeout: fromMaybe 0.0 $ (\(Milliseconds x) -> x) <$> req.timeout 232 | } 233 | 234 | extractContent :: RequestBody.RequestBody -> Either String Foreign 235 | extractContent = case _ of 236 | RequestBody.ArrayView f -> 237 | Right $ f (unsafeToForeign :: forall b. ArrayView b -> Foreign) 238 | RequestBody.Blob x -> 239 | Right $ (unsafeToForeign :: Blob -> Foreign) x 240 | RequestBody.Document x -> 241 | Right $ (unsafeToForeign :: Document -> Foreign) x 242 | RequestBody.String x -> 243 | Right $ (unsafeToForeign :: String -> Foreign) x 244 | RequestBody.FormData x -> 245 | Right $ (unsafeToForeign :: FormData -> Foreign) x 246 | RequestBody.FormURLEncoded x -> do 247 | note "Body contains values that cannot be encoded as application/x-www-form-urlencoded" 248 | $ (unsafeToForeign :: String -> Foreign) <$> FormURLEncoded.encode x 249 | RequestBody.Json x -> 250 | Right $ (unsafeToForeign :: String -> Foreign) (J.stringify x) 251 | 252 | headers :: Maybe RequestBody.RequestBody -> Array RequestHeader 253 | headers reqContent = 254 | addHeader (ContentType <$> (RequestBody.toMediaType =<< reqContent)) 255 | $ addHeader (Accept <$> ResponseFormat.toMediaType req.responseFormat) req.headers 256 | 257 | timeoutErrorMessageIdent :: String 258 | timeoutErrorMessageIdent = "AffjaxTimeoutErrorMessageIdent" 259 | 260 | requestFailedMessageIdent :: String 261 | requestFailedMessageIdent = "AffjaxRequestFailedMessageIdent" 262 | 263 | addHeader :: Maybe RequestHeader -> Array RequestHeader -> Array RequestHeader 264 | addHeader mh hs = case mh of 265 | Just h | not $ any (on eq RequestHeader.name h) hs -> hs `Arr.snoc` h 266 | _ -> hs 267 | 268 | parseJSON :: String -> Except (NEL.NonEmptyList ForeignError) Json 269 | parseJSON = case _ of 270 | "" -> pure J.jsonEmptyObject 271 | str -> either (fail <<< ForeignError) pure (jsonParser str) 272 | 273 | fromResponse :: Foreign -> Except (NEL.NonEmptyList ForeignError) a 274 | fromResponse = case req.responseFormat of 275 | ResponseFormat.ArrayBuffer _ -> unsafeReadTagged "ArrayBuffer" 276 | ResponseFormat.Blob _ -> unsafeReadTagged "Blob" 277 | ResponseFormat.Document _ -> \x -> 278 | unsafeReadTagged "Document" x 279 | <|> unsafeReadTagged "XMLDocument" x 280 | <|> unsafeReadTagged "HTMLDocument" x 281 | ResponseFormat.Json coe -> coe <<< parseJSON <=< unsafeReadTagged "String" 282 | ResponseFormat.String _ -> unsafeReadTagged "String" 283 | ResponseFormat.Ignore coe -> const $ coe (pure unit) 284 | 285 | type AjaxRequest :: Type -> Type 286 | type AjaxRequest a = 287 | { method :: String 288 | , url :: URL 289 | , headers :: Array { field :: String, value :: String } 290 | , content :: Nullable Foreign 291 | , responseType :: String 292 | , username :: Nullable String 293 | , password :: Nullable String 294 | , withCredentials :: Boolean 295 | , timeout :: Number 296 | } 297 | 298 | -- Drivers should have the following 'shape': 299 | -- ``` 300 | -- { newXHR :: Effect Xhr 301 | -- , fixupUrl :: Fn2 Xhr String String 302 | -- } 303 | -- ``` 304 | -- If you're adding a new environment (e.g. Electron), 305 | -- be sure to re-export all the types and functions 306 | -- in the `Affjax` module, so people can easily 307 | -- update their code by changing the imported module 308 | foreign import data AffjaxDriver :: Type 309 | 310 | foreign import _ajax 311 | :: forall a 312 | . Fn5 313 | AffjaxDriver 314 | String 315 | String 316 | (String -> String -> ResponseHeader) 317 | (AjaxRequest a) 318 | (AC.EffectFnAff (Response Foreign)) 319 | --------------------------------------------------------------------------------