Comparing version 2.1.2 to 3.0.0
@@ -1,19 +0,22 @@ | ||
export interface Request { | ||
export declare type Request<Body = any, CustomOptions extends object = any> = CustomOptions & { | ||
url: string; | ||
method?: Method; | ||
headers?: object; | ||
body?: any; | ||
cors?: boolean; | ||
method: HttpMethodLiteral | Method; | ||
headers?: HttpHeaderLiteral; | ||
body?: Body; | ||
withCredentials?: boolean; | ||
} | ||
export interface Response { | ||
}; | ||
export declare type Response<Body = any, CustomValues extends object = any> = CustomValues & { | ||
statusCode: number; | ||
headers: object; | ||
headers: HttpHeaderLiteral; | ||
contentType: string; | ||
xhr: XMLHttpRequest; | ||
body: any; | ||
} | ||
body: Body; | ||
}; | ||
export interface NextFunction<Response> { | ||
(): Promise<Response>; | ||
} | ||
export declare type HttpHeaderLiteral = { | ||
[key: string]: string | string[]; | ||
}; | ||
export declare type HttpMethodLiteral = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "UPDATE"; | ||
export declare enum Method { | ||
@@ -35,2 +38,2 @@ GET = "GET", | ||
export * from "./withHeader"; | ||
export * from "./withBearer"; | ||
export * from "./withAuth"; |
@@ -38,8 +38,11 @@ /*! ***************************************************************************** | ||
var output = {}; | ||
arr.forEach(function (line) { | ||
for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) { | ||
var line = arr_1[_i]; | ||
var parts = line.split(": "); | ||
var header = parts.shift(); | ||
var value = parts.join(": "); | ||
output[header] = value; | ||
}); | ||
if (!!header) { | ||
output[header] = value; | ||
} | ||
} | ||
// Return the object | ||
@@ -58,14 +61,19 @@ return output; | ||
xhr.open(request.method, request.url, true); | ||
xhr.withCredentials = request.withCredentials; | ||
xhr.withCredentials = !!request.withCredentials; | ||
// Add each header to the XHR request | ||
for (var k in request.headers) { | ||
xhr.setRequestHeader(k, request.headers[k]); | ||
if (typeof request.headers === "object") { | ||
for (var k in request.headers) { | ||
var value = request.headers[k]; | ||
xhr.setRequestHeader(k, (Array.isArray(value) ? | ||
value.join(", ") : | ||
value)); | ||
} | ||
} | ||
// Reject on error | ||
xhr.onerror = function (ev) { | ||
reject(ev.error); | ||
reject(ev.error || new Error("XHR request failed without reason.")); | ||
}; | ||
// Generate a formatted object for the response | ||
xhr.onload = function () { | ||
accept({ | ||
var res = { | ||
xhr: xhr, | ||
@@ -75,4 +83,5 @@ statusCode: xhr.status, | ||
headers: getAllHeaders(xhr), | ||
body: xhr.responseText | ||
}); | ||
body: xhr.responseText, | ||
}; | ||
accept(res); | ||
}; | ||
@@ -83,3 +92,2 @@ // Send the request | ||
} | ||
/** | ||
@@ -97,14 +105,9 @@ * Creates and returns a new "portal" instance for creating HTTP | ||
middleware = middleware.concat(send); | ||
return function (request) { | ||
return function portal(request) { | ||
// If the request body is a FormData object, set our Content-Type header | ||
var contentType = (request.body instanceof FormData ? "multipart/form-data" : "text/plain"); | ||
// The "cors" option is being deprecated in favor of the more properly | ||
// named "withCredentials" | ||
if (request.cors) { | ||
console.warn("DEPRECATION WARNING: Use `withCredentials` instead of `cors`."); | ||
} | ||
// Create a new copy of our request object so middleware doesn't mutate | ||
// a given object | ||
request = __assign({ method: "GET", withCredentials: (request.cors || false), headers: { | ||
"Content-Type": contentType | ||
request = __assign({ method: "GET", withCredentials: false, headers: { | ||
"Content-Type": contentType, | ||
} }, request); | ||
@@ -123,3 +126,3 @@ // If the request body is a FormData object, then we automatically set | ||
console.warn("Middleware fired its next() method more than once."); | ||
return; | ||
return Promise.reject(new Error("Middleware fired its next() method more than once.")); | ||
} | ||
@@ -137,3 +140,2 @@ // Track the last index that will fire | ||
} | ||
return next(0); | ||
@@ -151,2 +153,5 @@ }; | ||
(req.body instanceof Object || Array.isArray(req.body)))) { | ||
if (typeof req.headers !== "object") { | ||
req.headers = {}; | ||
} | ||
req.headers["Content-Type"] = "application/json"; | ||
@@ -178,3 +183,3 @@ req.body = JSON.stringify(req.body); | ||
var domain = matches && matches[1]; | ||
return (domain + prefix + url.replace(domain, '')); | ||
return (domain + prefix + url.replace(domain || "", "")); | ||
} | ||
@@ -207,2 +212,5 @@ else { | ||
var _a; | ||
if (typeof request.headers !== "object") { | ||
request.headers = {}; | ||
} | ||
if (override) { | ||
@@ -219,10 +227,14 @@ request.headers[name] = getValue(request); | ||
/** | ||
* Adds the Authorization header with the returned string as the bearer token. | ||
* Adds the Authorization header with the returned string as the header value. | ||
* Won't set the Authorization token if the result from getToken is falsey. | ||
*/ | ||
function withBearer(getToken) { | ||
function withAuthorization(getToken, prefix) { | ||
if (prefix === void 0) { prefix = ""; } | ||
return function (request, next) { | ||
var token = getToken(request); | ||
if (token) { | ||
request.headers["Authorization"] = "Bearer " + token; | ||
if (!!token) { | ||
if (typeof request.headers !== "object") { | ||
request.headers = {}; | ||
} | ||
request.headers["Authorization"] = prefix + token; | ||
} | ||
@@ -232,2 +244,9 @@ return next(); | ||
} | ||
/** | ||
* Adds the Authorization header with the returned string as the bearer token. | ||
* Won't set the Authorization token if the result from getToken is falsey. | ||
*/ | ||
function withBearer(getToken) { | ||
return withAuthorization(getToken, "Bearer "); | ||
} | ||
@@ -245,2 +264,2 @@ var Method; | ||
export { Method, getAllHeaders, send, createPortal, supportsJson, withPrefix, withHeader, withBearer }; | ||
export { Method, getAllHeaders, send, createPortal, supportsJson, withPrefix, withHeader, withAuthorization, withBearer }; |
@@ -42,8 +42,11 @@ 'use strict'; | ||
var output = {}; | ||
arr.forEach(function (line) { | ||
for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) { | ||
var line = arr_1[_i]; | ||
var parts = line.split(": "); | ||
var header = parts.shift(); | ||
var value = parts.join(": "); | ||
output[header] = value; | ||
}); | ||
if (!!header) { | ||
output[header] = value; | ||
} | ||
} | ||
// Return the object | ||
@@ -62,14 +65,19 @@ return output; | ||
xhr.open(request.method, request.url, true); | ||
xhr.withCredentials = request.withCredentials; | ||
xhr.withCredentials = !!request.withCredentials; | ||
// Add each header to the XHR request | ||
for (var k in request.headers) { | ||
xhr.setRequestHeader(k, request.headers[k]); | ||
if (typeof request.headers === "object") { | ||
for (var k in request.headers) { | ||
var value = request.headers[k]; | ||
xhr.setRequestHeader(k, (Array.isArray(value) ? | ||
value.join(", ") : | ||
value)); | ||
} | ||
} | ||
// Reject on error | ||
xhr.onerror = function (ev) { | ||
reject(ev.error); | ||
reject(ev.error || new Error("XHR request failed without reason.")); | ||
}; | ||
// Generate a formatted object for the response | ||
xhr.onload = function () { | ||
accept({ | ||
var res = { | ||
xhr: xhr, | ||
@@ -79,4 +87,5 @@ statusCode: xhr.status, | ||
headers: getAllHeaders(xhr), | ||
body: xhr.responseText | ||
}); | ||
body: xhr.responseText, | ||
}; | ||
accept(res); | ||
}; | ||
@@ -87,3 +96,2 @@ // Send the request | ||
} | ||
/** | ||
@@ -101,14 +109,9 @@ * Creates and returns a new "portal" instance for creating HTTP | ||
middleware = middleware.concat(send); | ||
return function (request) { | ||
return function portal(request) { | ||
// If the request body is a FormData object, set our Content-Type header | ||
var contentType = (request.body instanceof FormData ? "multipart/form-data" : "text/plain"); | ||
// The "cors" option is being deprecated in favor of the more properly | ||
// named "withCredentials" | ||
if (request.cors) { | ||
console.warn("DEPRECATION WARNING: Use `withCredentials` instead of `cors`."); | ||
} | ||
// Create a new copy of our request object so middleware doesn't mutate | ||
// a given object | ||
request = __assign({ method: "GET", withCredentials: (request.cors || false), headers: { | ||
"Content-Type": contentType | ||
request = __assign({ method: "GET", withCredentials: false, headers: { | ||
"Content-Type": contentType, | ||
} }, request); | ||
@@ -127,3 +130,3 @@ // If the request body is a FormData object, then we automatically set | ||
console.warn("Middleware fired its next() method more than once."); | ||
return; | ||
return Promise.reject(new Error("Middleware fired its next() method more than once.")); | ||
} | ||
@@ -141,3 +144,2 @@ // Track the last index that will fire | ||
} | ||
return next(0); | ||
@@ -155,2 +157,5 @@ }; | ||
(req.body instanceof Object || Array.isArray(req.body)))) { | ||
if (typeof req.headers !== "object") { | ||
req.headers = {}; | ||
} | ||
req.headers["Content-Type"] = "application/json"; | ||
@@ -182,3 +187,3 @@ req.body = JSON.stringify(req.body); | ||
var domain = matches && matches[1]; | ||
return (domain + prefix + url.replace(domain, '')); | ||
return (domain + prefix + url.replace(domain || "", "")); | ||
} | ||
@@ -211,2 +216,5 @@ else { | ||
var _a; | ||
if (typeof request.headers !== "object") { | ||
request.headers = {}; | ||
} | ||
if (override) { | ||
@@ -223,10 +231,14 @@ request.headers[name] = getValue(request); | ||
/** | ||
* Adds the Authorization header with the returned string as the bearer token. | ||
* Adds the Authorization header with the returned string as the header value. | ||
* Won't set the Authorization token if the result from getToken is falsey. | ||
*/ | ||
function withBearer(getToken) { | ||
function withAuthorization(getToken, prefix) { | ||
if (prefix === void 0) { prefix = ""; } | ||
return function (request, next) { | ||
var token = getToken(request); | ||
if (token) { | ||
request.headers["Authorization"] = "Bearer " + token; | ||
if (!!token) { | ||
if (typeof request.headers !== "object") { | ||
request.headers = {}; | ||
} | ||
request.headers["Authorization"] = prefix + token; | ||
} | ||
@@ -236,2 +248,9 @@ return next(); | ||
} | ||
/** | ||
* Adds the Authorization header with the returned string as the bearer token. | ||
* Won't set the Authorization token if the result from getToken is falsey. | ||
*/ | ||
function withBearer(getToken) { | ||
return withAuthorization(getToken, "Bearer "); | ||
} | ||
@@ -254,2 +273,3 @@ (function (Method) { | ||
exports.withHeader = withHeader; | ||
exports.withAuthorization = withAuthorization; | ||
exports.withBearer = withBearer; |
@@ -20,2 +20,2 @@ import { Request, Response, Middleware } from "./"; | ||
*/ | ||
export declare function createPortal<Req extends Request = Request, Res extends Response = Response>(...middleware: Middleware<Req, Res>[]): Portal<Req, Res>; | ||
export declare function createPortal<CustomRequestOptions extends object = any, CustomResponseValues extends object = any>(...middleware: Middleware<Request<any, CustomRequestOptions>, Response<any, CustomResponseValues>>[]): Portal<Request<any, CustomRequestOptions>, Response<any, CustomResponseValues>>; |
@@ -8,2 +8,2 @@ import { Request, Response, Middleware } from "./"; | ||
*/ | ||
export declare function supportsJson(): Middleware<Request & EncodeJSON, Response>; | ||
export declare function supportsJson(): Middleware<Request<any, EncodeJSON>, Response>; |
@@ -9,2 +9,2 @@ import { Request, Middleware } from "./"; | ||
*/ | ||
export declare function withHeader<Req extends Request = Request>(name: string, value: WithHeaderValue<Req>, override?: boolean): Middleware<Req, any>; | ||
export declare function withHeader<CustomRequestOptions extends object = any>(name: string, value: WithHeaderValue<Request<any, CustomRequestOptions>>, override?: boolean): Middleware<Request<any, CustomRequestOptions>, any>; |
{ | ||
"name": "portals", | ||
"version": "2.1.2", | ||
"version": "3.0.0", | ||
"description": "Client-side HTTP requests with middleware support.", | ||
@@ -9,3 +9,3 @@ "main": "dist/index.js", | ||
"scripts": { | ||
"preversion": "npm test", | ||
"preversion": "npm test && npm run lint", | ||
"version": "npm run build", | ||
@@ -15,2 +15,3 @@ "postversion": "git push origin master && git push origin master --tags", | ||
"build": "rollup -c", | ||
"lint": "tslint -p ./", | ||
"watch": "rollup -cw", | ||
@@ -48,2 +49,3 @@ "test": "jest", | ||
"ts-jest": "^22.4.6", | ||
"tslint": "^5.11.0", | ||
"typescript": "^2.9.2" | ||
@@ -50,0 +52,0 @@ }, |
@@ -9,3 +9,3 @@ ![Portals](logo.png) | ||
``` | ||
```sh | ||
npm install --save portals | ||
@@ -42,9 +42,9 @@ ``` | ||
Field | Type | Description | ||
------|------|------------ | ||
**url** | `string` | The endpoint address that we'll making a request to. **This field is required.** | ||
**method** | `string` | The HTTP method used for the request. _Defaults to `"GET"`._ | ||
**headers** | `object` | An object literal containing all of the HTTP headers for the request. Automatically gets mapped to the XHR object for the request. | ||
**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. | ||
**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`._ | ||
| Field | Type | Description | | ||
| ------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| **url** | `string` | The endpoint address that we'll making a request to. **This field is required.** | | ||
| **method** | `string` | The HTTP method used for the request. _Defaults to `"GET"`._ | | ||
| **headers** | `object` | An object literal containing all of the HTTP headers for the request. Automatically gets mapped to the XHR object for the request. | | ||
| **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. | | ||
| **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`._ | | ||
@@ -55,9 +55,9 @@ ### The Response Object | ||
Field | Type | Description | ||
------|------|------------ | ||
**xhr** | `XMLHttpRequest` | The XHR instance used to perform the request. | ||
**statusCode** | `number` | The HTTP status code returned by the server. Should be within the 200 - 299 for OK or accepted requests. | ||
**contentType** | `string` | The MIME type for the response provided by the `Content-Type` response header. | ||
**headers** | `object` | Response headers in a simplified object literal. | ||
**body** | `any` | The body of the response. | ||
| Field | Type | Description | | ||
| --------------- | ---------------- | --------------------------------------------------------------------------------------------------------- | | ||
| **xhr** | `XMLHttpRequest` | The XHR instance used to perform the request. | | ||
| **statusCode** | `number` | The HTTP status code returned by the server. Should be within the 200 - 299 for OK or accepted requests. | | ||
| **contentType** | `string` | The MIME type for the response provided by the `Content-Type` response header. | | ||
| **headers** | `object` | Response headers in a simplified object literal. | | ||
| **body** | `any` | The body of the response. | | ||
@@ -122,5 +122,19 @@ ### Error Handling | ||
### `withAuthorization(getToken)` | ||
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. | ||
```ts | ||
import {withAuthorization} from "portals"; | ||
withAuthorization(req => localStorage.getItem("apiToken")) | ||
// { headers: { Authorization: "${apiToken}" } } | ||
withAuthorization(req => localStorage.getItem("apiToken"), "Token ") | ||
// { headers: { Authorization: "Token ${apiToken}" } } | ||
``` | ||
### `withBearer(getToken)` | ||
Passes the `request` object to the given `getToken` method to generate an Bearer token for the `Authorization` header. | ||
Passes the `request` object to the given `getToken` method to generate a Bearer token for the `Authorization` header. | ||
@@ -127,0 +141,0 @@ ```ts |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
35319
13
629
143
8