Skip to content

Commit

Permalink
feat:  add support for lang in prepareQuery
Browse files Browse the repository at this point in the history
  • Loading branch information
nicholasio committed Jul 23, 2024
1 parent 7cf4563 commit 2fdcd75
Show file tree
Hide file tree
Showing 7 changed files with 136 additions and 17 deletions.
4 changes: 2 additions & 2 deletions packages/core/src/data/fetchFn/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { FetchOptions } from '../strategies';
import { EndpointParams, FetchOptions } from '../strategies';

export type QueryProps<P> = {
export type QueryProps<P extends EndpointParams> = {
path?: string;
params?: Partial<P>;
options?: Partial<FetchOptions>;
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/middlewares/__tests__/appMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ describe('appMiddleware', () => {
expect(getAppRouterLocale(req)).toBe('pt');

expect(res.headers.get('x-middleware-rewrite')).toBe(
'http://test2.com/test2.com/post-name',
'http://test2.com/pt/test2.com/post-name',
);
expect(res.headers.get('x-headstartwp-site')).toBe('test2.com');
expect(res.headers.get('x-headstartwp-locale')).toBe('pt');
Expand Down
18 changes: 12 additions & 6 deletions packages/next/src/middlewares/appMidleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ export function getAppRouterLocale(request: NextRequest) {

const locale = matchLocale(languages, locales, defaultLocale);

// get locale from URL

return locale;
}

Expand Down Expand Up @@ -132,16 +134,20 @@ export async function AppMiddleware(
return NextResponse.redirect(req.url.replace('/page/1', ''));
}

if (locale) {
// check to see if it needs to redirect
}

if (isMultisiteRequest) {
const url = req.nextUrl;

const pagesRouterRewrite = `/_sites/${hostname}${url.pathname}`;
const appRouterRewrite = locale
? `/${locale}/${hostname}${url.pathname}`
: `/${hostname}${url.pathname}`;

response = NextResponse.rewrite(
new URL(
options.appRouter
? `/${hostname}${url.pathname}`
: `/_sites/${hostname}${url.pathname}`,
url,
),
new URL(options.appRouter ? appRouterRewrite : pagesRouterRewrite, url),
);

response.headers.set('x-headstartwp-site', hostname);
Expand Down
92 changes: 91 additions & 1 deletion packages/next/src/rsc/data/queries/__tests__/prepareQuery.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { setHeadstartWPConfig } from '@headstartwp/core';
import { getHeadstartWPConfig, setHeadstartWPConfig } from '@headstartwp/core';
import { prepareQuery } from '../prepareQuery';

describe('prepareQuery', () => {
Expand Down Expand Up @@ -82,3 +82,93 @@ describe('prepareQuery', () => {
).toThrow('Sub site not found, make sure to add site3.com to headstartwp.config.js');
});
});

describe('prepareQuery with lang and multisite', () => {
beforeAll(() => {
setHeadstartWPConfig({
sites: [
{
sourceUrl: 'https://backend1.com',
hostUrl: 'https://site1.com',
locale: 'en',
},
{
sourceUrl: 'https://backend2.com',
hostUrl: 'https://site1.com',
locale: 'pt',
},
],
});
});

it('gets site correctly based on lang and host', () => {
expect(
prepareQuery({
routeParams: { site: 'site1.com', lang: 'pt' },
}),
).toMatchObject({
config: {
sourceUrl: 'https://backend2.com',
hostUrl: 'https://site1.com',
},
});

expect(
prepareQuery({
routeParams: { site: 'site1.com', lang: 'en' },
}),
).toMatchObject({
config: {
sourceUrl: 'https://backend1.com',
hostUrl: 'https://site1.com',
},
});
});
});

describe('prepareQuery with lang and polylang', () => {
beforeAll(() => {
setHeadstartWPConfig({
sourceUrl: 'https://backend1.com',
hostUrl: 'https://site1.com',
integrations: {
polylang: {
enable: true,
locales: ['en', 'pt'],
},
},
});
});

it('prepares params correctly', () => {
expect(
prepareQuery(
{
routeParams: { lang: 'pt' },
},
getHeadstartWPConfig(),
),
).toMatchObject({
config: {
sourceUrl: 'https://backend1.com',
hostUrl: 'https://site1.com',
},
params: {
lang: 'pt',
},
});
});

it('throws for unsuported locales', () => {
expect(() =>
prepareQuery(
{
routeParams: { lang: 'br' },
},
getHeadstartWPConfig(),
),
).toThrow(
'Unsuported lang, make sure you add all desired locales to `config.integrations.polylang.locales`',
);
});
});
28 changes: 25 additions & 3 deletions packages/next/src/rsc/data/queries/prepareQuery.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
EndpointParams,
FrameworkError,
HeadlessConfig,
getHeadstartWPConfig,
Expand All @@ -11,15 +12,20 @@ import type { NextQueryProps } from './types';

const { all: merge } = deepmerge;

export function prepareQuery<P>(
export function prepareQuery<P extends EndpointParams>(
query: NextQueryProps<P>,
_config: HeadlessConfig | undefined = undefined,
) {
const { routeParams, handleError = true, ...rest } = query;
const { routeParams, handleError = true, params: originalParams, ...rest } = query;

const path = routeParams?.path ?? '';
const site = decodeURIComponent(routeParams?.site ?? '');

// eslint-disable-next-line no-nested-ternary
const siteConfig = routeParams?.site
? getSiteByHost(decodeURIComponent(routeParams?.site))
? routeParams.lang
? getSiteByHost(site, routeParams.lang)
: getSiteByHost(site)
: null;

if (routeParams?.site && !siteConfig) {
Expand All @@ -40,8 +46,24 @@ export function prepareQuery<P>(
const config = siteConfig ?? _config;
const pathname = Array.isArray(path) ? convertToPath(path) : path;

const params: typeof originalParams =
typeof originalParams !== 'undefined' ? { ...originalParams } : {};

// if there's not a site config but there is lang
// and polylang integration is enabled then add lang
if (!siteConfig && routeParams?.lang && params && config?.integrations?.polylang?.enable) {
const supportedLocales = config.integrations.polylang.locales ?? [];
if (!supportedLocales.includes(routeParams.lang)) {
throw new FrameworkError(
'Unsuported lang, make sure you add all desired locales to `config.integrations.polylang.locales`',
);
}
params.lang = routeParams.lang;
}

return {
...rest,
params,
options,
path: pathname,
config: config ?? getHeadstartWPConfig(),
Expand Down
5 changes: 3 additions & 2 deletions packages/next/src/rsc/data/queries/types.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import type { QueryProps } from '@headstartwp/core';
import type { EndpointParams, QueryProps } from '@headstartwp/core';

export type NextQueryProps<P> = {
export type NextQueryProps<P extends EndpointParams> = {
routeParams?: {
path?: string | string[];
site?: string;
lang?: string;
[k: string]: unknown;
};
handleError?: boolean;
Expand Down
4 changes: 2 additions & 2 deletions packages/next/src/rsc/types.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
export type HeadstartWPRoute<Params extends { [k: string]: unknown } = {}> = {
params: { path: string[]; site?: string };
params: { path: string[]; site?: string; lang?: string };
} & Params;

export type HeadstartWPLayout<Params extends { [k: string]: unknown } = {}> = {
params: { site?: string };
params: { site?: string; lang?: string };
children: React.ReactNode;
} & Params;

0 comments on commit 2fdcd75

Please sign in to comment.