1 | ![Portals](logo.png)
|
2 |
|
3 | Portals is a library for making XHR requests with middleware support.
|
4 |
|
5 | ## Getting Started
|
6 |
|
7 | Install the library with `npm`:
|
8 |
|
9 | ```sh
|
10 | npm install --save portals
|
11 | ```
|
12 |
|
13 | Once installed, you can import the `createPortal()` function to get up and running immediately. This function is a factory that will set up a new "portal" for creating HTTP requests.
|
14 |
|
15 | ```ts
|
16 | import {createPortal} from "portals";
|
17 |
|
18 | const http = createPortal();
|
19 |
|
20 | http({ url: "http://example.com/some/endpoint" }).then(res => ...)
|
21 | ```
|
22 |
|
23 | The example above doesn't do much outside of creating an XHR request for you. However, the usefulness of this library lies in its use of [middleware](#middleware). The example below will stringify and parse JSON for the request and response data, prefix given URLs with the desired hostname and add the Authorization header with a Bearer token.
|
24 |
|
25 | > **Note:** Don't be afraid to have multiple portal functions for different use cases. The returned function is incredibly simple and contains little overhead.
|
26 |
|
27 | ```ts
|
28 | import {createPortal, supportsJson, withPrefix, withBearer} from "portals";
|
29 |
|
30 | const exampleApi = createPortal(
|
31 | supportsJson(),
|
32 | withPrefix("https://api.example.com")
|
33 | withBearer(req => localStorage.getItem("apiToken"))
|
34 | );
|
35 | ```
|
36 |
|
37 | ### The Request Object
|
38 |
|
39 | The table below outlines the fields supported by all requests, regardless of middleware.
|
40 |
|
41 | | Field | Type | Description |
|
42 | | ------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
43 | | **url** | `string` | The endpoint address that we'll making a request to. **This field is required.** |
|
44 | | **method** | `string` | The HTTP method used for the request. _Defaults to `"GET"`._ |
|
45 | | **headers** | `object` | An object literal containing all of the HTTP headers for the request. Automatically gets mapped to the XHR object for the request. |
|
46 | | **body** | `any` | The request body used by `POST`, `PUT` and `PATCH` requests. By default, you should use `string` or `FormData` formats unless you have middleware in place to handle type conversions. |
|
47 | | **withCredentials** | `boolean` | Sets the value of the `.withCredentials` property of the XHR instance for the request in order to allow secured cross-domain calls. _Defaults to `true`._ |
|
48 |
|
49 | ### The Response Object
|
50 |
|
51 | The table below represents the object generated for a response before middleware is applied.
|
52 |
|
53 | | Field | Type | Description |
|
54 | | --------------- | ---------------- | --------------------------------------------------------------------------------------------------------- |
|
55 | | **xhr** | `XMLHttpRequest` | The XHR instance used to perform the request. |
|
56 | | **statusCode** | `number` | The HTTP status code returned by the server. Should be within the 200 - 299 for OK or accepted requests. |
|
57 | | **contentType** | `string` | The MIME type for the response provided by the `Content-Type` response header. |
|
58 | | **headers** | `object` | Response headers in a simplified object literal. |
|
59 | | **body** | `any` | The body of the response. |
|
60 |
|
61 | ### Error Handling
|
62 |
|
63 | Because every endpoint handles errors differently, the errors that are reported to your Promise's `.catch()` handler are only for fatal errors related to problems within your middleware or the XHR call itself. Instead, you can check the status code on the response object that is returned.
|
64 |
|
65 | ## Middleware
|
66 |
|
67 | The middleware system employed by this library is based on Promises and should feel familiar to people who have used libraries with similar patterns (like [Koa](https://koajs.com)). Middleware in Portals is a function that accepts a `Request` object and a `next()` function that will invoke and return the result of the next middleware in the stack. The result of `next()` will _always_ be a `Promise`.
|
68 |
|
69 | > **Note:** Portals supports native promises and can safely be used with the `async/await` keywords.
|
70 |
|
71 | ```ts
|
72 | function myMiddleware(request, next) {
|
73 | // do something with the request
|
74 | return next().then(function(response) {
|
75 | // do something with the response
|
76 | });
|
77 | }
|
78 | ```
|
79 |
|
80 | ## Included Middleware
|
81 |
|
82 | ### `supportsJson()`
|
83 |
|
84 | Encodes object literal `body` values into JSON requests and automatically parses JSON response bodies.
|
85 |
|
86 | ### `withPrefix(prefix)`
|
87 |
|
88 | Prefix the request URL with either a full hostname or partial URI.
|
89 |
|
90 | ```ts
|
91 | import {withPrefix} from "portals";
|
92 |
|
93 | // converts `/foo` to `/api/foo` and...
|
94 | // converts `http://example.com` to `http://example.com/api`
|
95 | withPrefix("/api")
|
96 |
|
97 | // converts `/foo` to `http://example.com/foo` but
|
98 | // leaves `http://somewhere.else.com/foo` alone
|
99 | withPrefix("http://example.com")
|
100 | ```
|
101 |
|
102 | ### `withHeader(name, value, override = false)`
|
103 |
|
104 | Add a header to your request, either as a default if none is provided or as a constant override. The second argument, `value`, can also be a function that receives the `request` object.
|
105 |
|
106 | ```ts
|
107 | import {withHeader} from "portals";
|
108 |
|
109 | // Default header
|
110 | withHeader("Content-Type", "application/json")
|
111 |
|
112 | // Constant override header
|
113 | withHeader("Content-Type", "application/json", true)
|
114 |
|
115 | // Dynamic header value
|
116 | withHeader("Content-Type", (req) => (req.body instanceof FormData ? "multipart/form-data" : "application/json"))
|
117 | ```
|
118 |
|
119 | ### `withAuthorization(getToken)`
|
120 |
|
121 | Passes the `request` object to the given `getToken` method to generate a value for the `Authorization` header. Optionally supports a custom string `prefix` as the second value that is only applied when a string value is successfully returned from the `getToken` function call.
|
122 |
|
123 | ```ts
|
124 | import {withAuthorization} from "portals";
|
125 |
|
126 | withAuthorization(req => localStorage.getItem("apiToken"))
|
127 | // { headers: { Authorization: "${apiToken}" } }
|
128 |
|
129 | withAuthorization(req => localStorage.getItem("apiToken"), "Token ")
|
130 | // { headers: { Authorization: "Token ${apiToken}" } }
|
131 | ```
|
132 |
|
133 | ### `withBearer(getToken)`
|
134 |
|
135 | Passes the `request` object to the given `getToken` method to generate a Bearer token for the `Authorization` header.
|
136 |
|
137 | ```ts
|
138 | import {withBearer} from "portals";
|
139 |
|
140 | withBearer(req => localStorage.getItem("apiToken"))
|
141 | // { headers: { Authorization: "Bearer ${apiToken}" } }
|
142 | ```
|