Skip to content

Commit

Permalink
overhaul apifetch so it works
Browse files Browse the repository at this point in the history
  • Loading branch information
sirreal committed May 3, 2024
1 parent c90b723 commit 2a33146
Show file tree
Hide file tree
Showing 13 changed files with 76 additions and 80 deletions.
35 changes: 8 additions & 27 deletions packages/api-fetch/src/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@
/**
* Internal dependencies
*/
import fetchAllMiddleware from './middlewares/fetch-all-middleware';
import namespaceEndpointMiddleware from './middlewares/namespace-endpoint';
import httpV1Middleware from './middlewares/http-v1';
import userLocaleMiddleware from './middlewares/user-locale';
import {
parseResponseAndNormalizeError,
parseAndThrowError,
Expand Down Expand Up @@ -39,28 +35,6 @@ const DEFAULT_OPTIONS = {
credentials: 'include',
};

/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
/** @typedef {import('./types').APIFetchOptions} APIFetchOptions */

/**
* @type {import('./types').APIFetchMiddleware[]}
*/
const middlewares = [
userLocaleMiddleware,
namespaceEndpointMiddleware,
httpV1Middleware,
fetchAllMiddleware,
];

/**
* Register a middleware
*
* @param {import('./types').APIFetchMiddleware} middleware
*/
export function registerMiddleware( middleware ) {
middlewares.unshift( middleware );
}

/**
* Checks the status of a response, throwing the Response as an error if
* it is outside the 200 range.
Expand Down Expand Up @@ -142,12 +116,19 @@ export function setFetchHandler( newFetchHandler ) {
fetchHandler = newFetchHandler;
}

/** @type { typeof import('./middlewares/singleton').middlewares } */
let middlewares;

/**
* @template T
* @param {import('./types').APIFetchOptions} options
* @return {Promise<T>} A promise representing the request processed via the registered middlewares.
*/
export function apiFetch( options ) {
export async function apiFetch( options ) {
if ( ! middlewares ) {
middlewares = ( await import( './middlewares/singleton' ) ).middlewares;
}

// creates a nested function chain that calls all middlewares and finally the `fetchHandler`,
// converting `middlewares = [ m1, m2, m3 ]` into:
// ```
Expand Down
17 changes: 9 additions & 8 deletions packages/api-fetch/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
/**
* Internal dependencies
*/
import createNonceMiddleware from './middlewares/nonce';
import createRootURLMiddleware from './middlewares/root-url';
import createPreloadingMiddleware from './middlewares/preloading';
import fetchAllMiddleware from './middlewares/fetch-all-middleware';
import mediaUploadMiddleware from './middlewares/media-upload';
import createThemePreviewMiddleware from './middlewares/theme-preview';
import { createNonceMiddleware } from './middlewares/nonce';
import { createRootURLMiddleware } from './middlewares/root-url';
import { createPreloadingMiddleware } from './middlewares/preloading';
import { fetchAllMiddleware } from './middlewares/fetch-all-middleware';
import { mediaUploadMiddleware } from './middlewares/media-upload';
import { createThemePreviewMiddleware } from './middlewares/theme-preview';
import * as ApiFetchCore from './core';
import { type APIFetchOptions } from './types';
import { registerMiddleware } from './middlewares/singleton';

export interface ApiFetch {
< T >( options: APIFetchOptions ): Promise< T >;
use: typeof ApiFetchCore.registerMiddleware;
use: typeof registerMiddleware;
setFetchHandler: typeof ApiFetchCore.setFetchHandler;
createNonceMiddleware: typeof createNonceMiddleware;
createPreloadingMiddleware: typeof createPreloadingMiddleware;
Expand All @@ -25,7 +26,7 @@ export interface ApiFetch {
// @ts-expect-error This is an incomplete type we'll add properties to.
const apiFetch: ApiFetch = ApiFetchCore.apiFetch;

apiFetch.use = ApiFetchCore.registerMiddleware;
apiFetch.use = registerMiddleware;
apiFetch.setFetchHandler = ApiFetchCore.setFetchHandler;
apiFetch.createNonceMiddleware = createNonceMiddleware;
apiFetch.createPreloadingMiddleware = createPreloadingMiddleware;
Expand Down
8 changes: 3 additions & 5 deletions packages/api-fetch/src/middlewares/fetch-all-middleware.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* Internal dependencies
*/
import apiFetch from '..';
import { apiFetch } from '../core';

/**
* Apply query arguments to both URL and Path, whichever is present.
Expand All @@ -11,7 +11,7 @@ import apiFetch from '..';
* @return {import('../types').APIFetchOptions} The request with the modified query args
*/
const modifyQuery = ( { path, url, ...options }, queryArgs ) => {
/** @type {import('../core').APIFetchOptions} */
/** @type {import('../types').APIFetchOptions} */
const result = {
...options,
};
Expand Down Expand Up @@ -98,7 +98,7 @@ const requestContainsUnboundedQuery = ( options ) => {
*
* @type {import('../types').APIFetchMiddleware}
*/
const fetchAllMiddleware = async ( options, next ) => {
export const fetchAllMiddleware = async ( options, next ) => {
if ( options.parse === false ) {
// If a consumer has opted out of parsing, do not apply middleware.
return next( options );
Expand Down Expand Up @@ -148,5 +148,3 @@ const fetchAllMiddleware = async ( options, next ) => {
}
return mergedResults;
};

export default fetchAllMiddleware;
4 changes: 1 addition & 3 deletions packages/api-fetch/src/middlewares/http-v1.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const DEFAULT_METHOD = 'GET';
*
* @type {import('../types').APIFetchMiddleware}
*/
const httpV1Middleware = ( options, next ) => {
export const httpV1Middleware = ( options, next ) => {
const { method = DEFAULT_METHOD } = options;
if ( OVERRIDE_METHODS.has( method.toUpperCase() ) ) {
options = {
Expand All @@ -39,5 +39,3 @@ const httpV1Middleware = ( options, next ) => {

return next( options );
};

export default httpV1Middleware;
4 changes: 1 addition & 3 deletions packages/api-fetch/src/middlewares/media-upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ function isMediaUploadRequest( options ) {
*
* @type {import('../types').APIFetchMiddleware}
*/
const mediaUploadMiddleware = ( options, next ) => {
export const mediaUploadMiddleware = ( options, next ) => {
if ( ! isMediaUploadRequest( options ) ) {
return next( options );
}
Expand Down Expand Up @@ -89,5 +89,3 @@ const mediaUploadMiddleware = ( options, next ) => {
parseResponseAndNormalizeError( response, options.parse )
);
};

export default mediaUploadMiddleware;
4 changes: 1 addition & 3 deletions packages/api-fetch/src/middlewares/namespace-endpoint.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* @type {import('../types').APIFetchMiddleware}
*/
const namespaceAndEndpointMiddleware = ( options, next ) => {
export const namespaceEndpointMiddleware = ( options, next ) => {
let path = options.path;
let namespaceTrimmed, endpointTrimmed;

Expand All @@ -26,5 +26,3 @@ const namespaceAndEndpointMiddleware = ( options, next ) => {
path,
} );
};

export default namespaceAndEndpointMiddleware;
4 changes: 1 addition & 3 deletions packages/api-fetch/src/middlewares/nonce.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* @param {string} nonce
* @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce.
*/
function createNonceMiddleware( nonce ) {
export function createNonceMiddleware( nonce ) {
/**
* @type {import('../types').APIFetchMiddleware & { nonce: string }}
*/
Expand Down Expand Up @@ -33,5 +33,3 @@ function createNonceMiddleware( nonce ) {

return middleware;
}

export default createNonceMiddleware;
4 changes: 1 addition & 3 deletions packages/api-fetch/src/middlewares/preloading.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* @param {Record<string, any>} preloadedData
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
function createPreloadingMiddleware( preloadedData ) {
export function createPreloadingMiddleware( preloadedData ) {
const cache = Object.fromEntries(
Object.entries( preloadedData ).map( ( [ path, data ] ) => [
path,
Expand Down Expand Up @@ -68,5 +68,3 @@ function prepareResponse( responseData, parse ) {
} )
);
}

export default createPreloadingMiddleware;
8 changes: 3 additions & 5 deletions packages/api-fetch/src/middlewares/root-url.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
/**
* Internal dependencies
*/
import namespaceAndEndpointMiddleware from './namespace-endpoint';
import { namespaceEndpointMiddleware } from './namespace-endpoint';

/**
* @param {string} rootURL
* @return {import('../types').APIFetchMiddleware} Root URL middleware.
*/
const createRootURLMiddleware = ( rootURL ) => ( options, next ) => {
return namespaceAndEndpointMiddleware( options, ( optionsWithPath ) => {
export const createRootURLMiddleware = ( rootURL ) => ( options, next ) => {
return namespaceEndpointMiddleware( options, ( optionsWithPath ) => {
let url = optionsWithPath.url;
let path = optionsWithPath.path;
let apiRoot;
Expand Down Expand Up @@ -40,5 +40,3 @@ const createRootURLMiddleware = ( rootURL ) => ( options, next ) => {
} );
} );
};

export default createRootURLMiddleware;
26 changes: 26 additions & 0 deletions packages/api-fetch/src/middlewares/singleton.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Internal dependencies
*/
import { fetchAllMiddleware } from './fetch-all-middleware';
import { namespaceEndpointMiddleware } from './namespace-endpoint';
import { httpV1Middleware } from './http-v1';
import { userLocaleMiddleware } from './user-locale';

/**
* @type {import('../types').APIFetchMiddleware[]}
*/
export const middlewares = [
userLocaleMiddleware,
namespaceEndpointMiddleware,
httpV1Middleware,
fetchAllMiddleware,
];

/**
* Register a middleware
*
* @param {import('../types').APIFetchMiddleware} middleware
*/
export function registerMiddleware( middleware ) {
middlewares.unshift( middleware );
}
4 changes: 1 addition & 3 deletions packages/api-fetch/src/middlewares/theme-preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
*
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
const createThemePreviewMiddleware = () => ( options, next ) => {
export const createThemePreviewMiddleware = () => ( options, next ) => {
return next( options );
};

export default createThemePreviewMiddleware;
4 changes: 1 addition & 3 deletions packages/api-fetch/src/middlewares/user-locale.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
/**
* @type {import('../types').APIFetchMiddleware}
*/
const userLocaleMiddleware = ( options, next ) => {
export const userLocaleMiddleware = ( options, next ) => {
return next( options );
};

export default userLocaleMiddleware;
34 changes: 20 additions & 14 deletions packages/api-fetch/src/wp-module.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
/**
* Internal dependencies
*/
import createNonceMiddleware from './middlewares/nonce';
import createRootURLMiddleware from './middlewares/root-url';
import createPreloadingMiddleware from './middlewares/preloading';
import fetchAllMiddleware from './middlewares/fetch-all-middleware';
import mediaUploadMiddleware from './middlewares/media-upload';
import createThemePreviewMiddleware from './middlewares/theme-preview';
import { apiFetch, registerMiddleware, setFetchHandler } from './core';
import { createNonceMiddleware } from './middlewares/nonce';
import { createRootURLMiddleware } from './middlewares/root-url';
import { createPreloadingMiddleware } from './middlewares/preloading';
import { fetchAllMiddleware } from './middlewares/fetch-all-middleware';
import { mediaUploadMiddleware } from './middlewares/media-upload';
import { createThemePreviewMiddleware } from './middlewares/theme-preview';
import { apiFetch, setFetchHandler } from './core';
import { registerMiddleware } from './middlewares/singleton';

if ( typeof document !== 'undefined' ) {
const el = document.getElementById( 'scriptmoduledata_@wordpress/api-fetch' );
const el = document.getElementById(
'wp-scriptmodule-data_@wordpress/api-fetch'
);
if ( el?.textContent ) {
console.group( 'api-fetch init' );
try {
Expand All @@ -34,15 +37,18 @@ if ( typeof document !== 'undefined' ) {
apiFetch.nonceEndpoint = config.nonceEndpoint;
}
if ( config.themePreviewPath ) {
// @ts-expect-error This is wrong, done for testing.
registerMiddleware( createThemePreviewMiddleware( config.themePreviewPath ) );
registerMiddleware(
// @ts-expect-error This is wrong, done for testing.
createThemePreviewMiddleware( config.themePreviewPath )
);
}
if ( config.preloadData ) {
registerMiddleware( createPreloadingMiddleware( config.preloadData ) );
registerMiddleware(
createPreloadingMiddleware( config.preloadData )
);
}

} catch {
console.error( 'error' );
} catch ( err ) {
console.error( err );
} finally {
console.groupEnd();
}
Expand Down

0 comments on commit 2a33146

Please sign in to comment.