Skip to content

Commit

Permalink
feat: use window.fetch with polyfill instead of jquery (#5whc87)
Browse files Browse the repository at this point in the history
  • Loading branch information
matzeeable committed Jun 19, 2020
1 parent 7db5a07 commit 3c31b59
Show file tree
Hide file tree
Showing 14 changed files with 287 additions and 684 deletions.
64 changes: 47 additions & 17 deletions packages/utils/lib/factory/ajax/commonRequest.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import $ from "jquery";
import {
WP_REST_API_USE_GLOBAL_METHOD,
RouteRequestInterface,
Expand All @@ -8,6 +7,9 @@ import {
commonUrlBuilder,
RouteHttpVerb
} from "./";
import deepMerge from "deepmerge";
import Url from "url-parse";
import "whatwg-fetch"; // window.fetch polyfill

/**
* Build and execute a specific REST query.
Expand All @@ -17,37 +19,65 @@ import {
* @throws
*/
async function commonRequest<
Request extends RouteRequestInterface,
Params extends RouteParamsInterface,
Response extends RouteResponseInterface
TRequest extends RouteRequestInterface,
TParams extends RouteParamsInterface,
TResponse extends RouteResponseInterface
>({
location,
options,
request: routeRequest,
params,
settings = {}
}: {
request?: Request;
params?: Params;
settings?: JQuery.AjaxSettings<any>;
} & RequestArgs): Promise<Response> {
request?: TRequest;
params?: TParams;
settings?: Partial<{ -readonly [P in keyof Request]: Request[P] }>;
} & RequestArgs): Promise<TResponse> {
const url = commonUrlBuilder({ location, params, nonce: false, options });

// Use global parameter (see https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/)
if (WP_REST_API_USE_GLOBAL_METHOD && location.method && location.method !== RouteHttpVerb.GET) {
settings.method = "POST";
} else {
settings.method = "GET";
}

const result = await $.ajax(
$.extend(true, settings, {
url,
headers: {
"X-WP-Nonce": options.restNonce
},
data: routeRequest
})
// Request with GET/HEAD method cannot have body
const apiUrl = new Url(url, true);
const allowBody = ["HEAD", "GET"].indexOf(settings.method) === -1;
if (!allowBody && routeRequest) {
apiUrl.set("query", deepMerge(apiUrl.query, routeRequest));
}

const result = await window.fetch(
apiUrl.toString(),
deepMerge.all([
settings,
{
headers: {
"Content-Type": "application/json;charset=utf-8",
"X-WP-Nonce": options.restNonce
},
body: allowBody ? JSON.stringify(routeRequest) : undefined
}
])
);
return result as Response;

// `window.fetch` does not throw an error if the server response an error code.
if (!result.ok) {
let responseJSON = undefined;
try {
responseJSON = await result.json();
} catch (e) {
// Silence is golden.
}

const resultAny = result as any;
resultAny.responseJSON = responseJSON;
throw resultAny;
}

return (await result.json()) as TResponse;
}

export { commonRequest };
14 changes: 3 additions & 11 deletions packages/utils/lib/factory/ajax/commonUrlBuilder.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
import Url from "url-parse";
import $ from "jquery";
import { trailingslashit, untrailingslashit } from "../../helpers";
import { BaseOptions } from "../../options";
import { RouteHttpVerb } from ".";
import deepMerge from "deepmerge";

// Use _method instead of Http verb
const WP_REST_API_USE_GLOBAL_METHOD = true;

enum RouteHttpVerb {
GET = "GET",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE",
PATCH = "PATCH"
}

interface RouteLocationInterface {
path: string;
namespace?: string;
Expand Down Expand Up @@ -89,12 +82,11 @@ function commonUrlBuilder({
query._method = location.method;
}

return apiUrl.set("query", $.extend(true, {}, options.restQuery, getParams, query)).toString();
return apiUrl.set("query", deepMerge.all([options.restQuery, getParams, query])).toString();
}

export {
WP_REST_API_USE_GLOBAL_METHOD,
RouteHttpVerb,
RouteLocationInterface,
RouteRequestInterface,
RouteParamsInterface,
Expand Down
1 change: 1 addition & 0 deletions packages/utils/lib/factory/ajax/index.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from "./commonUrlBuilder";
export * from "./commonRequest";
export * from "./createRequestFactory";
export * from "./routeHttpVerbEnum";
9 changes: 9 additions & 0 deletions packages/utils/lib/factory/ajax/routeHttpVerbEnum.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
enum RouteHttpVerb {
GET = "GET",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE",
PATCH = "PATCH"
}

export { RouteHttpVerb };
9 changes: 5 additions & 4 deletions packages/utils/lib/factory/i18n.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @see https://github.com/Automattic/wp-calypso/blob/master/packages/i18n-calypso/src/index.js

import { ReactNode } from "react";
import * as i18nCalypso from "i18n-calypso";
import { ReactNode, ReactElement } from "react";
import interpolate from "interpolate-components";
import * as wpi18n from "@wordpress/i18n";
import wp from "wp";

Expand Down Expand Up @@ -75,8 +75,9 @@ function createLocalizationFactory(slug: string) {
* A translation can look like this: "Hello {{a}}click me{{/a}}." and you have to pass
* a component with key "a".
*/
function _i(translation: string, components?: i18nCalypso.TranslateOptions["components"]): any {
return i18nCalypso.translate(translation, {
function _i(translation: string, components?: { [placeholder: string]: ReactElement }): any {
return interpolate({
mixedString: translation,
components
}) as ReactNode;
}
Expand Down
6 changes: 4 additions & 2 deletions packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -122,16 +122,18 @@
"@wordpress/i18n": "^3.6.1",
"classnames": "^2.2.6",
"core-js": "3",
"deepmerge": "^4.2.2",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"i18n-calypso": "^4.0.0",
"immer": "^6.0.2",
"interpolate-components": "^1.1.1",
"jquery": "^3.4.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-test-renderer": "^16.13.1",
"setimmediate": "^1.0.5",
"url-parse": "^1.4.7"
"url-parse": "^1.4.7",
"whatwg-fetch": "^3.0.0"
},
"devDependencies": {
"@babel/core": "^7.9.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/utils/src/Assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public function enqueueReact() {
public function enqueueUtils() {
$this->enqueueReact();
$this->enqueueMobx();
$scriptDeps = [self::$HANDLE_REACT, self::$HANDLE_REACT_DOM, self::$HANDLE_MOBX, 'moment', 'wp-i18n', 'jquery'];
$scriptDeps = [self::$HANDLE_REACT, self::$HANDLE_REACT_DOM, self::$HANDLE_MOBX, 'wp-i18n', 'jquery'];
$handleUtils = $this->enqueueComposerScript('utils', $scriptDeps);
array_push($scriptDeps, $handleUtils);
return $scriptDeps;
Expand Down
Loading

0 comments on commit 3c31b59

Please sign in to comment.