|
| 1 | +import { Language } from "@dzcode.io/models/dist/language"; |
| 2 | +import { Response } from "express"; |
| 3 | +import { plainLocalize } from "@dzcode.io/web/dist/components/locale/utils"; |
| 4 | +import { dictionary, AllDictionaryKeys } from "@dzcode.io/web/dist/components/locale/dictionary"; |
| 5 | +import { fetchV2Factory } from "@dzcode.io/utils/dist/fetch/factory"; |
| 6 | +import { Endpoints } from "@dzcode.io/api/dist/app/endpoints"; |
| 7 | +import { fullstackConfig } from "src/utils/config"; |
| 8 | +import { getContributionURL } from "@dzcode.io/web/dist/utils/contribution"; |
| 9 | +import { templateContent } from "./templates"; |
| 10 | +import { notFoundPath } from "src/utils/paths"; |
| 11 | + |
| 12 | +export const renderContributionPage = async ( |
| 13 | + res: Response, |
| 14 | + lang: Language, |
| 15 | + contributionId: string, |
| 16 | +) => { |
| 17 | + const localize = (key: AllDictionaryKeys) => |
| 18 | + plainLocalize(dictionary, lang.code, key, "NO-TRANSLATION"); |
| 19 | + const fetchV2 = fetchV2Factory<Endpoints>(fullstackConfig, lang.code); |
| 20 | + |
| 21 | + try { |
| 22 | + const { contribution } = await fetchV2("api:contributions/:id/title", { |
| 23 | + params: { id: contributionId }, |
| 24 | + }); |
| 25 | + const pageTitle = `${localize("contribution-title-pre")} ${contribution.title} ${localize("contribution-title-post")}`; |
| 26 | + |
| 27 | + const newData = templateContent |
| 28 | + .replace(/{{template-title}}/g, pageTitle) |
| 29 | + .replace(/{{template-description}}/g, localize("contribute-description")) |
| 30 | + .replace(/{{template-lang}}/g, lang.code) |
| 31 | + .replace( |
| 32 | + /{{template-canonical}}/g, |
| 33 | + getContributionURL({ id: contributionId, title: contribution.title }, lang), |
| 34 | + ); |
| 35 | + |
| 36 | + res.setHeader("Content-Type", "text/html; charset=utf-8"); |
| 37 | + res.status(200).send(newData); |
| 38 | + } catch (error) { |
| 39 | + // @TODO-ZM: log error to loki |
| 40 | + console.error(error); |
| 41 | + res.status(404).sendFile(notFoundPath); |
| 42 | + } |
| 43 | +}; |
0 commit comments