Skip to content

Commit

Permalink
Merge branch 'master' into params-serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
developit authored Jul 15, 2020
2 parents 7d3cb5d + bfff330 commit 0747987
Show file tree
Hide file tree
Showing 9 changed files with 249 additions and 53 deletions.
1 change: 0 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,3 @@ insert_final_newline = true
[{*.json,*.md,.*rc,*.yml,*.txt}]
indent_style = space
indent_size = 2
insert_final_newline = false
9 changes: 4 additions & 5 deletions .github/workflows/compressed-size.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ on: [pull_request]

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- uses: preactjs/compressed-size-action@v1
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
- uses: actions/checkout@v2
- uses: preactjs/compressed-size-action@v1
with:
repo-token: '${{ secrets.GITHUB_TOKEN }}'
31 changes: 18 additions & 13 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
name: CI

on: [push]
on:
push:
branches:
- master
pull_request:
branches:
- master

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: 12
- name: npm install, build, and test
run: |
npm install
npm run prepare --if-present
npm test
env:
CI: true
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: 12
- name: npm install, build, and test
run: |
npm install
npm run prepare --if-present
npm test
env:
CI: true
4 changes: 4 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
package-lock.json
dist
coverage
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ information on using pull requests.
## Community Guidelines

This project follows [Google's Open Source Community
Guidelines](https://opensource.google.com/conduct/).
Guidelines](https://opensource.google.com/conduct/).
39 changes: 35 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,44 @@
"main": "dist/redaxios.js",
"umd:main": "dist/redaxios.umd.js",
"module": "dist/redaxios.module.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "microbundle",
"test": "eslint src test && karmatic",
"release": "npm t && git commit -am \"$npm_package_version\" && git tag $npm_package_version && git push && git push --tags && npm publish"
"build": "microbundle && tsc",
"test": "npm run format:check && eslint src test && karmatic",
"release": "npm t && git commit -am \"$npm_package_version\" && git tag $npm_package_version && git push && git push --tags && npm publish",
"format": "prettier --write './**/*.{js,json,yml,md}'",
"format:check": "prettier --check './**/*.{js,json,yml,md}'"
},
"files": [
"dist",
"src"
],
"eslintConfig": {
"extends": "developit"
"extends": [
"developit",
"prettier"
],
"rules": {
"jest/no-jasmine-globals": "off"
}
},
"prettier": {
"arrowParens": "always",
"trailingComma": "none",
"singleQuote": true,
"endOfLine": "lf",
"useTabs": true,
"printWidth": 120,
"overrides": [
{
"files": "**/*.json",
"options": {
"parser": "json-stringify",
"useTabs": false,
"tabWidth": 2
}
}
]
},
"repository": "developit/redaxios",
"keywords": [
Expand All @@ -27,14 +54,18 @@
"license": "Apache-2.0",
"homepage": "https://github.com/developit/redaxios",
"devDependencies": {
"core-js": "2.6.11",
"eslint": "^6.8.0",
"eslint-config-developit": "^1.1.1",
"eslint-config-prettier": "6.11.0",
"file-loader": "^5.0.2",
"isomorphic-fetch": "^2.2.1",
"jest": "^24.9.0",
"karmatic": "^1.4.0",
"microbundle": "^0.11.0",
"prettier": "2.0.5",
"sinon": "^8.0.4",
"typescript": "3.9.3",
"webpack": "^4.41.5"
}
}
87 changes: 67 additions & 20 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,19 @@
* @public
* @typedef Options
* @property {string} [url] the URL to request
* @property {string} [method="get"] HTTP method, case-insensitive
* @property {'get'|'post'|'put'|'patch'|'delete'|'options'|'head'|'GET'|'POST'|'PUT'|'PATCH'|'DELETE'|'OPTIONS'|'HEAD'} [method="get"] HTTP method, case-insensitive
* @property {Headers} [headers] Request headers
* @property {FormData|string|object} [body] a body, optionally encoded, to send
* @property {'text'|'json'|'stream'|'blob'|'arrayBuffer'|'formData'|'stream'} [responseType="text"] An encoding to use for the response
* @property {boolean} [withCredentials] Send the request with credentials like cookies
* @property {string} [auth] Authorization header value to send with the request
* @property {string} [xsrfCookieName] Pass an Cross-site Request Forgery prevention cookie value as a header defined by `xsrfHeaderName`
* @property {string} [xsrfHeaderName] The name of a header to use for passing XSRF cookies
* @property {(status: number) => boolean} [validateStatus] Override status code handling (default: 200-399 is a success)
* @property {Array<(body: any, headers: Headers) => any?>} [transformRequest] An array of transformations to apply to the outgoing request
* @property {string} [baseURL] a base URL from which to resolve all URLs
* @property {typeof window.fetch} [fetch] Custom window.fetch implementation
* @property {any} [data]
*/

/**
Expand All @@ -34,20 +38,30 @@

/**
* @public
* @template T
* @typedef Response
* @property {number} status
* @property {string} statusText
* @property {Options} config the request configuration
* @property {any} data the decoded response body
* @property {T} data the decoded response body
* @property {Headers} headers
* @property {boolean} redirect
* @property {string} url
* @property {ResponseType} type
* @property {ReadableStream<Uint8Array> | null} body
* @property {boolean} bodyUsed
*/

/** */
export default (function create(defaults) {
export default (function create(/** @type {Options} */ defaults) {
defaults = defaults || {};

/**
* Creates a request factory bound to the given HTTP method.
* @private
* @template T
* @param {string} method
* @returns {(url: string, config?: Options) => Promise<Response>}
* @returns {<T=any>(url: string, config?: Options) => Promise<Response<T>>}
*/
function createBodylessMethod(method) {
return (url, config) => redaxios(url, Object.assign({ method }, config));
Expand All @@ -56,8 +70,9 @@ export default (function create(defaults) {
/**
* Creates a request factory bound to the given HTTP method.
* @private
* @template T
* @param {string} method
* @returns {(url: string, body?: any, config?: Options) => Promise<Response>}
* @returns {<T=any>(url: string, body?: any, config?: Options) => Promise<Response<T>>}
*/
function createBodyMethod(method) {
return (url, data, config) => redaxios(url, Object.assign({ method, data }, config));
Expand Down Expand Up @@ -91,7 +106,8 @@ export default (function create(defaults) {

/**
* @public
* @type {((config?: Options) => Promise<Response>) | ((url: string, config?: Options) => Promise<Response>)}
* @template T
* @type {(<T = any>(config?: Options) => Promise<Response<T>>) | (<T = any>(url: string, config?: Options) => Promise<Response<T>>)}
*/
redaxios.request = redaxios;

Expand All @@ -116,19 +132,32 @@ export default (function create(defaults) {
/** @public */
redaxios.all = Promise.all;

/** @public */
redaxios.spread = function(fn) {
/**
* @public
* @template T,R
* @param {(...args: T[]) => R} fn
* @returns {(array: T[]) => R}
*/
redaxios.spread = function (fn) {
return function (results) {
return fn.apply(this, results);
};
};

/**
* @private
* @param {Record<string,any>} opts
* @param {Record<string,any>} overrides
* @param {boolean} [lowerCase]
* @returns {Record<string,any>}
*/
function deepMerge(opts, overrides, lowerCase) {
if (Array.isArray(opts)) {
return opts.concat(overrides);
}
if (overrides && typeof overrides == 'object') {
let out = {}, i;
let out = /** @type {Record<string,any>} */ ({}),
i;
if (opts) {
for (i in opts) {
let key = lowerCase ? i.toLowerCase() : i;
Expand All @@ -148,15 +177,20 @@ export default (function create(defaults) {
/**
* Issues a request.
* @public
* @param {string} [url]
* @template T
* @param {string | Options} url
* @param {Options} [config]
* @returns {Promise<Response>}
* @returns {Promise<Response<T>>}
*/
function redaxios(url, config) {
if (typeof url !== 'string') {
config = url;
url = config.url;
}

/**
* @type {Options}
*/
const options = deepMerge(defaults, config || {});
let data = options.data;
url = buildUrl(url, options.params, options.paramsSerializer);
Expand All @@ -171,9 +205,12 @@ export default (function create(defaults) {
}

const fetchFunc = options.fetch || fetch;
/**
* @type {{'Content-Type':'application/json';Authorization: string} & Headers}
*/
const customHeaders = {};

if (data && typeof data === 'object') {
if (data && typeof data === 'object' && typeof data.append !== 'function') {
data = JSON.stringify(data);
customHeaders['Content-Type'] = 'application/json';
}
Expand All @@ -182,7 +219,7 @@ export default (function create(defaults) {
let parts = document.cookie.split(/ *[;=] */);
for (let i = 0; i < parts.length; i += 2) {
if (parts[i] == options.xsrfCookieName) {
customHeaders[options.xsrfHeaderName] = decodeURIComponent(parts[i+1]);
customHeaders[options.xsrfHeaderName] = decodeURIComponent(parts[i + 1]);
break;
}
}
Expand All @@ -192,15 +229,19 @@ export default (function create(defaults) {
customHeaders.Authorization = options.auth;
}

/** @type {Response} */
if (options.baseURL) {
url = new URL(url, options.baseURL) + '';
}

/** @type {Response<any>} */
const response = {};
response.config = config;
response.config = /** @type {Options} */ (config);

return fetchFunc(url, {
method: options.method,
body: data,
headers: deepMerge(options.headers, customHeaders, true),
credentials: options.withCredentials && 'include'
credentials: options.withCredentials ? 'include' : undefined
}).then((res) => {
let i;
for (i in res) {
Expand All @@ -209,18 +250,24 @@ export default (function create(defaults) {
if (!(options.validateStatus ? options.validateStatus(res.status) : res.ok)) {
return Promise.reject(res);
}
const withData = options.responseType === 'stream'
? Promise.resolve(res.body)
: res[options.responseType || 'text']();
const withData =
options.responseType === 'stream' ? Promise.resolve(res.body) : res[options.responseType || 'text']();
return withData.then((data) => {
response.data = data;
return response;
});
});
}

redaxios.CancelToken = self.AbortController || Object;
/**
* @public
* @type {AbortController}
*/
redaxios.CancelToken = /** @type {any} */ (typeof AbortController === 'function' ? AbortController : Object);

/**
* @public
*/
redaxios.create = create;

return redaxios;
Expand Down
Loading

0 comments on commit 0747987

Please sign in to comment.