Skip to content

refactor(blog): do not use static paths file #450

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 0 additions & 29 deletions apps/blog/scripts/build-routes.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const API_BASE_URL = process.env.AL_API_URL;
const BASE_URL = process.env.AL_BASE_URL;
const SSG_ROUTES_FILE_PATH = 'apps/blog/routes.txt';
const SITEMAP_FILE_PATH = 'apps/blog/src/sitemap.xml';
const ROOT_PATHS_FILE_PREFIX = 'apps/blog/src/assets/root-paths';
const BANNERS_FILE_PREFIX = 'apps/blog/src/assets/banners';

const SUPPORTED_LANGUAGES = ['pl', 'en'];
Expand Down Expand Up @@ -182,33 +181,6 @@ function writeSSGRoutesToFile() {
writeNextRoute();
}

/**
* Creates a static JSON asset with allowed article paths for a given language.
* @param {"pl" | "en"} lang
*/
function writeArticlePathsToFile(lang) {
const stream = createWriteStream(`${ROOT_PATHS_FILE_PREFIX}-${lang}.json`, {
encoding: 'utf-8',
});

stream.on('error', (error) => {
console.error('Error writing paths to file:', error);
});

const filteredArticlePaths = articleRoutes
.filter((pathObj) => pathObj.url.startsWith(`/${lang}/`))
.map((pathObj) => pathObj.url.replace(`/${lang}/`, ''));

try {
stream.write(JSON.stringify({ articles: filteredArticlePaths }));
} catch (error) {
console.error('Error during write operation:', error);
throw error;
} finally {
stream.end();
}
}

async function main() {
try {
await Promise.all([
Expand All @@ -219,7 +191,6 @@ async function main() {

SUPPORTED_LANGUAGES.forEach((lang) => {
appendStaticRoutes(lang);
writeArticlePathsToFile(lang);
});

writeSSGRoutesToFile();
Expand Down
28 changes: 26 additions & 2 deletions libs/blog-contracts/articles/src/lib/articles.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { AuthorTitle } from '@angular-love/blog/contracts/authors';

import { DbLang, Lang } from './languages';

export const articleCategories = [
'news',
'guides',
Expand Down Expand Up @@ -99,6 +101,8 @@ export const statusMap = {
private: ArticleStatus.Private,
} as const;

export type ArticleLocale = 'en_GB' | 'pl_PL';

export interface Article {
id: number;
title: string;
Expand All @@ -120,9 +124,29 @@ export interface Article {
};
anchors: Anchor[];
otherTranslations: {
locale: string;
locale: ArticleLocale;
slug: string;
}[];
lang: string;
language: DbLang;
seo: SeoData;
}

export const dbLocaleMap = {
en_GB: DbLang.English,
pl_PL: DbLang.Polish,
} as const;

export const dbLangMap = {
en: DbLang.English,
pl: DbLang.Polish,
} as const;

export const articleLangToLangMap = {
[DbLang.English]: 'en',
[DbLang.Polish]: 'pl',
} as const satisfies Record<DbLang, Lang>;

export const articleLangToLocaleMap = {
[DbLang.English]: 'en_GB',
[DbLang.Polish]: 'pl_PL',
} as const satisfies Record<DbLang, ArticleLocale>;
10 changes: 0 additions & 10 deletions libs/blog-contracts/articles/src/lib/languages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,6 @@ export const enum DbLang {
Polish = 2,
}

export const dbLocaleMap = {
en_GB: DbLang.English,
pl_PL: DbLang.Polish,
} as const;

export const dbLangMap = {
en: DbLang.English,
pl: DbLang.Polish,
} as const;

export const LangSchema = v.picklist(['pl', 'en'], 'Invalid lang');

export type Lang = v.InferInput<typeof LangSchema>;
Original file line number Diff line number Diff line change
@@ -1,56 +1,35 @@
import { HttpClient } from '@angular/common/http';
import { inject, isDevMode } from '@angular/core';
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { TranslocoService } from '@jsverse/transloco';
import { catchError, map, of } from 'rxjs';

import { AlLocalizeService } from '@angular-love/blog/i18n/util';
import { AlI18nService, AlLocalizeService } from '@angular-love/blog/i18n/util';
import { articleLangToLangMap } from '@angular-love/contracts/articles';

import { ArticleDetailsStore } from '../state/article-details.store';

export const articleExistsGuard: CanActivateFn = (route) => {
// bypass for local development
if (isDevMode()) return true;

const http = inject(HttpClient);
const router = inject(Router);
const transloco = inject(TranslocoService);
const i18nService = inject(AlI18nService);
const localizeService = inject(AlLocalizeService);

const { articleDetails, alternativeLanguageSlug } =
inject(ArticleDetailsStore);

const notFoundPageUrlTree = router.createUrlTree(
localizeService.localizePath(['/', '404']),
);

return http
.get<{
articles: string[];
}>(`/assets/root-paths-${transloco.getActiveLang()}.json`)
.pipe(
map((data) => {
const slug = route.paramMap.get('articleSlug');

if (slug && data.articles.includes(slug)) {
return true;
}

// check if the article is in the alternative language
if (articleDetails()?.lang !== transloco.getActiveLang()) {
// if the article is in the alternative language, redirect to the alternative language page
if (alternativeLanguageSlug()) {
return router.createUrlTree(
localizeService.localizePath(['/', alternativeLanguageSlug()]),
{},
);
} else return router.createUrlTree([`/${transloco.getActiveLang()}`]);
}

return notFoundPageUrlTree;
}),
catchError(() => {
return of(notFoundPageUrlTree);
}),
const article = articleDetails();
const alternativeSlug = alternativeLanguageSlug();

if (
article &&
route.url.length > 0 &&
route.url[0].path === article.slug &&
articleLangToLangMap[article.language] &&
articleLangToLangMap[article.language] !== i18nService.getActiveLang() &&
alternativeSlug
) {
return router.createUrlTree(
localizeService.localizePath(['/', alternativeSlug]),
{},
);
}

return true;
};
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ <h2 id="article-title" class="flex text-[40px] font-bold">
<al-article-share-icons
[slug]="articleDetails().slug"
[title]="articleDetails().title"
[language]="articleDetails().lang"
[locale]="locale()"
/>
</div>
</al-card>
Expand Down Expand Up @@ -83,7 +83,7 @@ <h2 id="article-title" class="flex text-[40px] font-bold">
<al-article-share-icons
[slug]="articleDetails().slug"
[title]="articleDetails().title"
[language]="articleDetails().lang"
[locale]="locale()"
/>
</div>
</al-card>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { DatePipe, NgClass } from '@angular/common';
import {
ChangeDetectionStrategy,
Component,
computed,
input,
signal,
} from '@angular/core';
Expand All @@ -24,7 +25,10 @@ import {
GradientCardDirective,
} from '@angular-love/blog/shared/ui-card';
import { UiDifficultyComponent } from '@angular-love/blog/shared/ui-difficulty';
import { Article } from '@angular-love/contracts/articles';
import {
Article,
articleLangToLocaleMap,
} from '@angular-love/contracts/articles';
import { RepeatDirective } from '@angular-love/utils';

import { ArticleShareIconsComponent } from '../article-share-icons/article-share-icons.component';
Expand Down Expand Up @@ -58,4 +62,8 @@ import { ArticleShareIconsComponent } from '../article-share-icons/article-share
export class ArticleDetailsComponent {
readonly articleDetails = input.required<Article>();
protected readonly adBannerStoreVisible = signal(false);

readonly locale = computed(
() => articleLangToLocaleMap[this.articleDetails().language],
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { TranslocoDirective } from '@jsverse/transloco';
import { FastSvgComponent } from '@push-based/ngx-fast-svg';

import { IconType } from '@angular-love/blog/shared/ui-icon';
import { ArticleLocale } from '@angular-love/contracts/articles';

type ShareItem = {
href: string;
Expand Down Expand Up @@ -59,12 +60,12 @@ type ShareItem = {
export class ArticleShareIconsComponent {
readonly slug = input.required<string>();
readonly title = input.required<string>();
readonly language = input.required<string>();
readonly locale = input.required<ArticleLocale>();

readonly animating = signal(false);

readonly articleUrl = computed(() =>
this.language() === 'pl_PL'
this.locale() === 'pl_PL'
? `https://angular.love/pl/${this.slug()}`
: `https://angular.love/${this.slug()}`,
);
Expand Down
3 changes: 2 additions & 1 deletion libs/blog/i18n/data-access/src/lib/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import localePl from '@angular/common/locales/pl';
import { isDevMode, LOCALE_ID } from '@angular/core';
import { provideTransloco } from '@jsverse/transloco';

import { AlLocalizeService } from '@angular-love/blog/i18n/util';
import { AlI18nService, AlLocalizeService } from '@angular-love/blog/i18n/util';

import { I18nHeadersInterceptor } from './i18n-headers.interceptor';
import { LocaleIdProvider } from './locale-id.provider';
Expand All @@ -31,5 +31,6 @@ export const provideI18n = () => {
},
{ provide: LOCALE_ID, useClass: LocaleIdProvider },
AlLocalizeService,
AlI18nService,
];
};
1 change: 1 addition & 0 deletions libs/blog/i18n/util/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './lib/localize.pipe';
export * from './lib/localize.service';
export * from './lib/i18n.service';
24 changes: 24 additions & 0 deletions libs/blog/i18n/util/src/lib/i18n.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { inject, Injectable } from '@angular/core';
import { TranslocoService } from '@jsverse/transloco';
import * as v from 'valibot';

import { Lang, LangSchema } from '@angular-love/contracts/articles';

@Injectable()
export class AlI18nService {
private readonly _transloco = inject(TranslocoService);

getActiveLang(): Lang {
const activeLang = this._transloco.getActiveLang();
const result = v.safeParse(LangSchema, activeLang);

if (!result.success) {
console.warn(
`Invalid active language "${activeLang}", defaulting to "en".`,
);
return 'en';
}

return result.output;
}
}