Skip to content

Commit

Permalink
refactor(i18n): add better types to our custom defineMessages (#1192)
Browse files Browse the repository at this point in the history
  • Loading branch information
gauthier-th authored Dec 28, 2024
1 parent 9a59529 commit 66948b4
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 13 deletions.
4 changes: 3 additions & 1 deletion src/components/Discover/DiscoverTvUpcoming.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import defineMessages from '@app/utils/defineMessages';
import type { TvResult } from '@server/models/Search';
import { useIntl } from 'react-intl';

const messages = defineMessages('components.DiscoverTvUpcoming', {});
const messages = defineMessages('components.DiscoverTvUpcoming', {
upcomingtv: 'Upcoming Series',
});

const DiscoverTvUpcoming = () => {
const intl = useIntl();
Expand Down
1 change: 1 addition & 0 deletions src/i18n/locale/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
"components.Discover.StudioSlider.studios": "Studios",
"components.Discover.TvGenreList.seriesgenres": "Series Genres",
"components.Discover.TvGenreSlider.tvgenres": "Series Genres",
"components.DiscoverTvUpcoming.upcomingtv": "Upcoming Series",
"components.Discover.createnewslider": "Create New Slider",
"components.Discover.customizediscover": "Customize Discover",
"components.Discover.discover": "Discover",
Expand Down
32 changes: 20 additions & 12 deletions src/utils/defineMessages.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
import { defineMessages as intlDefineMessages } from 'react-intl';

export default function defineMessages(
type Messages<T extends Record<string, string>> = {
[K in keyof T]: {
id: string;
defaultMessage: T[K];
};
};

export default function defineMessages<T extends Record<string, string>>(
prefix: string,
messages: Record<string, string>
) {
const modifiedMessages: Record<
string,
{ id: string; defaultMessage: string }
> = {};
for (const key of Object.keys(messages)) {
modifiedMessages[key] = {
id: prefix + '.' + key,
messages: T
): Messages<T> {
const keys: (keyof T)[] = Object.keys(messages);
const modifiedMessagesEntries = keys.map((key) => [
key,
{
id: `${prefix}.${key as string}`,
defaultMessage: messages[key],
};
}
},
]);
const modifiedMessages: Messages<T> = Object.fromEntries(
modifiedMessagesEntries
);
return intlDefineMessages(modifiedMessages);
}

0 comments on commit 66948b4

Please sign in to comment.