Skip to content

Commit

Permalink
feat: use strapi translations
Browse files Browse the repository at this point in the history
Only merge after digitalservicebund/a2j-rechtsantragstelle-strapi#184

Co-Authored-By: SannyNguyenHung <[email protected]>
Co-Authored-By: Joschka <[email protected]>
Co-Authored-By: Pram Gurusinga <[email protected]>
  • Loading branch information
4 people committed Dec 1, 2023
1 parent 4535936 commit ea28cf2
Show file tree
Hide file tree
Showing 13 changed files with 61 additions and 20 deletions.
2 changes: 1 addition & 1 deletion app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export const loader = async ({ request, context }: LoaderFunctionArgs) => {
fetchSingleEntry("cookie-banner"),
hasTrackingConsent({ request }),
getErrorPages(),
fetchMeta({ slug: "/" }),
fetchMeta({ filterValue: "/" }),
]);

return json({
Expand Down
4 changes: 2 additions & 2 deletions app/routes/beratungshilfe.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { throw404IfFeatureFlagEnabled } from "~/services/errorPages/throw404";
export async function loader({ request }: LoaderFunctionArgs) {
await throw404IfFeatureFlagEnabled(request);
const { pathname } = new URL(request.url);
const slug = `/${pathname.split("/").at(1) ?? ""}`;
return json({ meta: await fetchMeta({ slug }) });
const filterValue = `/${pathname.split("/").at(1) ?? ""}`;
return json({ meta: await fetchMeta({ filterValue }) });
}

export default function View() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ export const loader = async ({ params, request }: LoaderFunctionArgs) => {

// Remove PLZ from slug
const { pathname } = new URL(request.url);
const slug = pathname.substring(0, pathname.lastIndexOf("/"));
const filterValue = pathname.substring(0, pathname.lastIndexOf("/"));
const [common, meta] = await Promise.all([
fetchSingleEntry("amtsgericht-common"),
fetchMeta({ slug }),
fetchMeta({ filterValue }),
]);

const resultListHeading = fillTemplate({
Expand Down
4 changes: 3 additions & 1 deletion app/routes/shared/result.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ export const loader = async ({
const [common, cmsData, parentMeta, amtsgerichtCommon] = await Promise.all([
fetchSingleEntry("vorab-check-common"),
fetchCollectionEntry("result-pages", slug),
fetchMeta({ slug: pathname.substring(0, pathname.lastIndexOf("/")) }),
fetchMeta({
filterValue: pathname.substring(0, pathname.lastIndexOf("/")),
}),
fetchSingleEntry("amtsgericht-common"),
]);

Expand Down
6 changes: 4 additions & 2 deletions app/routes/shared/step.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,9 @@ export const loader = async ({
const [commonContent, formPageContent, parentMeta] = await Promise.all([
fetchSingleEntry("vorab-check-common"),
fetchCollectionEntry(currentFlow.cmsSlug, lookupPath),
fetchMeta({ slug: lookupPath.substring(0, lookupPath.lastIndexOf("/")) }),
fetchMeta({
filterValue: lookupPath.substring(0, lookupPath.lastIndexOf("/")),
}),
]);

// To add a <legend> inside radio groups, we extract the text from the first <h1> and replace any null labels with it
Expand Down Expand Up @@ -131,7 +133,7 @@ export const loader = async ({
const navigationLabels = Object.fromEntries(
await Promise.all(
getSubflowsEntries(currentFlow.flow).map(([subflowName]) =>
fetchMeta({ slug: `/${flowId}/${subflowName}` }).then(
fetchMeta({ filterValue: `/${flowId}/${subflowName}` }).then(
(meta) => [subflowName, meta.title] as [string, string],
),
),
Expand Down
7 changes: 5 additions & 2 deletions app/services/cms/getStrapiEntryFromApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import type { StrapiFileContent } from "./models/StrapiFileContent";

const buildUrl = ({
apiId,
slug,
pageSize,
filterField = "slug",
filterValue,
locale = defaultLocale,
populate = "deep",
}: GetStrapiEntryOpts) =>
Expand All @@ -18,7 +19,9 @@ const buildUrl = ({
`?populate=${populate}`,
`&locale=${locale}`,
pageSize ? `&pagination[pageSize]=${pageSize}` : "",
slug ? `&filters[slug][$eq]=${slug}` : "",
filterField && filterValue
? `&filters[${filterField}][$eq]=${filterValue}`
: "",
].join("");

type SingleStrapiEntry =
Expand Down
4 changes: 2 additions & 2 deletions app/services/cms/getStrapiEntryFromFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ export const getStrapiEntryFromFile = async ({
return false;

return !(
opts.slug &&
opts.filterValue &&
"slug" in item.attributes &&
item.attributes.slug !== opts.slug
item.attributes.slug !== opts.filterValue
);
})?.attributes;
};
28 changes: 24 additions & 4 deletions app/services/cms/index.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import { collectionSchemas, entrySchemas } from "./schemas";

export type GetStrapiEntryOpts = {
apiId: keyof StrapiFileContent;
slug?: string;
filterField?: string;
filterValue?: string;
locale?: StrapiLocale;
populate?: string;
pageSize?: string;
Expand All @@ -37,18 +38,37 @@ export async function fetchCollectionEntry<
ApiId extends keyof CollectionSchemas,
>(
apiId: ApiId,
slug: string,
filterValue: string,
filterField = "slug",
locale?: StrapiLocale,
): Promise<z.infer<CollectionSchemas[ApiId]>> {
const strapiEntry = await getStrapiEntry({ apiId, locale, slug });
const strapiEntry = await getStrapiEntry({
apiId,
locale,
filterValue,
filterField,
});

if (!strapiEntry) {
const error = new Error(`page missing in cms: ${slug}`);
const error = new Error(
`page missing in cms: ${filterField}:${filterValue}`,
);
error.name = "StrapiPageNotFound";
throw error;
}
return collectionSchemas[apiId].parse(strapiEntry);
}

export const strapiTranslation = async (
name: string,
locale?: StrapiLocale,
) => {
const entry = fetchCollectionEntry("translations", name, "scope", locale);
return Object.fromEntries(
(await entry).field.map(({ name, value }) => [name, value]),
);
};

export const strapiPageFromRequest = async ({
request,
locale,
Expand Down
6 changes: 6 additions & 0 deletions app/services/cms/models/StrapiFileContent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { StrapiCookieBannerSchema } from "./StrapiCookieBannerSchema";
import { StrapiPageHeaderSchema } from "./StrapiPageHeader";
import { StrapiGlobalSchema } from "./StrapiGlobal";
import { StrapiFormFlowPageSchema } from "./StrapiFormFlowPage";
import { StrapiTranslationSchema } from "./StrapiTranslations";

export const StrapiFileContentSchema = z.object({
"amtsgericht-common": z.array(
Expand Down Expand Up @@ -62,6 +63,11 @@ export const StrapiFileContentSchema = z.object({
attributes: StrapiFormFlowPageSchema,
}),
),
translations: z.array(
HasStrapiIdSchema.extend({
attributes: StrapiTranslationSchema,
}),
),
});

export type StrapiFileContent = z.infer<typeof StrapiFileContentSchema>;
5 changes: 5 additions & 0 deletions app/services/cms/models/StrapiTranslations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { z } from "zod";

export const StrapiTranslationSchema = z.object({
field: z.array(z.object({ name: z.string(), value: z.string() })),
});
2 changes: 2 additions & 0 deletions app/services/cms/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { StrapiCookieBannerSchema } from "./models/StrapiCookieBannerSchema";
import { StrapiPageHeaderSchema } from "./models/StrapiPageHeader";
import { StrapiGlobalSchema } from "./models/StrapiGlobal";
import { StrapiFormFlowPageSchema } from "./models/StrapiFormFlowPage";
import { StrapiTranslationSchema } from "./models/StrapiTranslations";

export const entrySchemas = {
"page-header": StrapiPageHeaderSchema,
Expand All @@ -24,5 +25,6 @@ export const collectionSchemas = {
"result-pages": StrapiResultPageSchema,
"vorab-check-pages": StrapiVorabCheckPageSchema,
"form-flow-pages": StrapiFormFlowPageSchema,
translations: StrapiTranslationSchema,
} as const;
export type CollectionSchemas = typeof collectionSchemas;
2 changes: 1 addition & 1 deletion tests/unit/services/cms/getStrapiEntryFromApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ describe("services/cms", () => {
mockedAxios.get
.mockResolvedValue(defaultResponseData)
.mockResolvedValueOnce(emptyResponseData);
await getStrapiEntryFromApi({ ...defaultOptions, slug: "foobar" });
await getStrapiEntryFromApi({ ...defaultOptions, filterValue: "foobar" });
expect(axiosGetSpy).toHaveBeenNthCalledWith(
1,
`${expectedStagingRequestUrl}&filters[slug][$eq]=foobar`,
Expand Down
7 changes: 4 additions & 3 deletions tests/unit/services/cms/getStrapiEntryFromFile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ describe("services/cms", () => {
"vorab-check-common": [],
"vorab-check-pages": [],
"form-flow-pages": [],
translations: [],
} satisfies StrapiFileContent;

(fs.readFileSync as jest.Mock).mockReturnValue(JSON.stringify(fileContent));
Expand Down Expand Up @@ -61,7 +62,7 @@ describe("services/cms", () => {
expect(
await getStrapiEntryFromFile({
apiId: "pages",
slug: "/impressum",
filterValue: "/impressum",
locale: "de",
}),
).toEqual(impressum);
Expand All @@ -72,7 +73,7 @@ describe("services/cms", () => {
expect(
await getStrapiEntryFromFile({
apiId: "pages",
slug: "/NOTAVAILABLE",
filterValue: "/NOTAVAILABLE",
locale: "de",
}),
).toBeUndefined();
Expand All @@ -84,7 +85,7 @@ describe("services/cms", () => {
expect(
await getStrapiEntryFromFile({
apiId: "pages",
slug: "/impressum",
filterValue: "/impressum",
locale: "en",
}),
).toBeUndefined();
Expand Down

0 comments on commit ea28cf2

Please sign in to comment.