|
|
import page from '@automattic/calypso-router'; |
|
|
import { getUrlParts } from '@automattic/calypso-url'; |
|
|
import { QueryClient } from '@tanstack/react-query'; |
|
|
import debugFactory from 'debug'; |
|
|
import { Store } from 'redux'; |
|
|
|
|
|
const debug = debugFactory( 'calypso' ); |
|
|
|
|
|
export const setupContextMiddleware = ( reduxStore: Store, reactQueryClient: QueryClient ) => { |
|
|
let previousPath: string | null = null; |
|
|
|
|
|
page( '*', ( context, next ) => { |
|
|
const parsed = getUrlParts( context.path ); |
|
|
|
|
|
context.previousPath = previousPath; |
|
|
previousPath = context.path; |
|
|
|
|
|
context.query = Object.fromEntries( parsed.searchParams.entries() ); |
|
|
context.pathname = parsed.pathname; |
|
|
|
|
|
context.hashstring = ( parsed.hash && parsed.hash.substring( 1 ) ) || ''; |
|
|
|
|
|
if ( context.hashstring ) { |
|
|
try { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
context.hash = Object.fromEntries( |
|
|
new globalThis.URLSearchParams( context.hashstring ).entries() |
|
|
); |
|
|
} catch ( e ) { |
|
|
debug( 'failed to query-string parse `location.hash`', e ); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
context.hash = {}; |
|
|
} |
|
|
} else { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
context.hash = {}; |
|
|
} |
|
|
|
|
|
context.store = reduxStore; |
|
|
context.queryClient = reactQueryClient; |
|
|
|
|
|
|
|
|
context.redirect = ( httpCode: number, newUrl: null | string | number = null ) => { |
|
|
if ( isNaN( httpCode ) && ! newUrl ) { |
|
|
newUrl = httpCode; |
|
|
} |
|
|
|
|
|
return page.replace( newUrl as string, context.state, false, false ); |
|
|
}; |
|
|
|
|
|
|
|
|
if ( context.pathname === '/wp-login.php' ) { |
|
|
window.location.href = context.path; |
|
|
return; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
next(); |
|
|
} ); |
|
|
|
|
|
page.exit( '*', ( context, next ) => { |
|
|
context.store = reduxStore; |
|
|
context.queryClient = reactQueryClient; |
|
|
|
|
|
next(); |
|
|
} ); |
|
|
}; |
|
|
|