Skip to content

Commit

Permalink
Throw for missing params in localized pathnames
Browse files Browse the repository at this point in the history
  • Loading branch information
amannn committed Nov 14, 2023
1 parent dc91509 commit 00f0998
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
12 changes: 11 additions & 1 deletion packages/next-intl/src/navigation/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,9 @@ export function compileLocalizedPathname<Locales extends AllLocales, Pathname>({
function compilePath(
namedPath: Pathnames<Locales>[keyof Pathnames<Locales>]
) {
let compiled =
const template =
typeof namedPath === 'string' ? namedPath : namedPath[locale];
let compiled = template;

if (params) {
Object.entries(params).forEach(([key, value]) => {
Expand All @@ -122,6 +123,15 @@ export function compileLocalizedPathname<Locales extends AllLocales, Pathname>({
});
}

if (process.env.NODE_ENV !== 'production' && compiled.includes('[')) {
// Next.js throws anyway, therefore better provide a more helpful error message
throw new Error(
`Insufficient params provided for localized pathname.\nTemplate: ${template}\nParams: ${JSON.stringify(
params
)}`
);
}

if (query) {
compiled += serializeSearchParams(query);
}
Expand Down
26 changes: 25 additions & 1 deletion packages/next-intl/test/navigation/utils.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import {describe, expect, it} from 'vitest';
import {serializeSearchParams} from '../../src/navigation/utils';
import {
compileLocalizedPathname,
serializeSearchParams
} from '../../src/navigation/utils';

describe('serializeSearchParams', () => {
it('handles strings', () => {
Expand All @@ -18,3 +21,24 @@ describe('serializeSearchParams', () => {
expect(serializeSearchParams({v: ['a', 'b']})).toEqual('?v=a&v=b');
});
});

describe('compileLocalizedPathname', () => {
it('throws when params were not resolved', () => {
const locales: ReadonlyArray<string> = ['en'];
expect(() =>
// @ts-expect-error -- Purposefully miss a param
compileLocalizedPathname<typeof locales, '/test/[one]/[two]'>({
locale: 'en',
pathname: '/test/[one]/[two]',
pathnames: '/test/[one]/[two]',
params: {one: '1'}
})
).toThrow(
[
'Insufficient params provided for localized pathname.',
'Template: /test/[one]/[two]',
'Params: {"one":"1"}'
].join('\n')
);
});
});

0 comments on commit 00f0998

Please sign in to comment.