Skip to content
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

feat(blog): pages #313

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions apps/blog-bff/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { articles } from '@angular-love/blog-bff/articles/api';
import { authors } from '@angular-love/blog-bff/authors/api';
import { banners } from '@angular-love/blog-bff/banners/api';
import { newsletter } from '@angular-love/blog-bff/newsletter/api';
import { pages } from '@angular-love/blog-bff/pages/api';

const app = new Hono();

Expand All @@ -23,6 +24,7 @@ Disallow: /`;
'Content-Type': 'text/plain',
});
});
app.route('/pages', pages);

app.onError((err, c) => {
console.error(err);
Expand Down
2 changes: 2 additions & 0 deletions apps/blog/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
routes.txt
src/sitemap.xml
Empty file removed apps/blog/routes.txt
Empty file.
41 changes: 37 additions & 4 deletions apps/blog/scripts/build-routes.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const ssgRoutes = [];
* @type {Array<{url: string, publishDate: string}>}
*/
const articleRoutes = [];
const pageRoutes = [];

/**
* Constructs a URL for a given path and language.
Expand Down Expand Up @@ -100,6 +101,29 @@ async function fetchAuthorRoutes(lang, skip = 0, take = 50) {
}
}

/**
* Fetches pages paths and appends them to the routes array.
* @param {"pl" | "en"} lang
* @returns {Promise<void>}
*/
async function fetchPageRoutes(lang) {
const url = `${API_BASE_URL}/pages`;
try {
const { data } = await fetch(url).then((resp) => resp.json());
const pageSlugs = data
.filter((page) => page.lang === lang)
.map((page) => ({
url: constructUrl(page.slug, lang),
publishDate: new Date().toISOString(),
}));
ssgRoutes.push(...pageSlugs);
pageRoutes.push(...pageSlugs);
} catch (error) {
console.error(`Failed to fetch pages from ${url}`);
throw error;
}
}

/**
* Appends static paths to the routes array for a given language.
* @param {"pl" | "en"} lang
Expand Down Expand Up @@ -145,10 +169,10 @@ function writeSSGRoutesToFile() {
}

/**
* Creates a static JSON asset with allowed article paths for a given language.
* Creates a static JSON asset with allowed article & pages paths for a given language.
* @param {"pl" | "en"} lang
*/
function writeArticlePathsToFile(lang) {
function writePathsToFile(lang) {
const stream = createWriteStream(`${ROOT_PATHS_FILE_PREFIX}-${lang}.json`, {
encoding: 'utf-8',
});
Expand All @@ -160,9 +184,17 @@ function writeArticlePathsToFile(lang) {
const filteredArticlePaths = articleRoutes
.filter((pathObj) => pathObj.url.startsWith(`/${lang}/`))
.map((pathObj) => pathObj.url.replace(`/${lang}/`, ''));
const filteredPagePaths = pageRoutes
.filter((pathObj) => pathObj.url.startsWith(`/${lang}/`))
.map((pathObj) => pathObj.url.replace(`/${lang}/`, ''));

try {
stream.write(JSON.stringify({ articles: filteredArticlePaths }));
stream.write(
JSON.stringify({
articles: filteredArticlePaths,
pages: filteredPagePaths,
}),
);
} catch (error) {
console.error('Error during write operation:', error);
throw error;
Expand All @@ -176,11 +208,12 @@ async function main() {
await Promise.all([
...SUPPORTED_LANGUAGES.map((lang) => fetchArticleRoutes(lang)),
...SUPPORTED_LANGUAGES.map((lang) => fetchAuthorRoutes(lang)),
...SUPPORTED_LANGUAGES.map((lang) => fetchPageRoutes(lang)),
]);

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

writeSSGRoutesToFile();
Expand Down
1 change: 1 addition & 0 deletions apps/blog/src/assets/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
root-paths-*.json
Empty file removed apps/blog/src/sitemap.xml
Empty file.
36 changes: 36 additions & 0 deletions libs/blog-bff/pages/api/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"extends": ["../../../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts"],
"extends": [
"plugin:@nx/angular",
"plugin:@angular-eslint/template/process-inline-templates"
],
"rules": {
"@angular-eslint/directive-selector": [
"error",
{
"type": "attribute",
"prefix": "al",
"style": "camelCase"
}
],
"@angular-eslint/component-selector": [
"error",
{
"type": "element",
"prefix": "al",
"style": "kebab-case"
}
]
}
},
{
"files": ["*.html"],
"extends": ["plugin:@nx/angular-template"],
"rules": {}
}
]
}
7 changes: 7 additions & 0 deletions libs/blog-bff/pages/api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# api

This library was generated with [Nx](https://nx.dev).

## Running unit tests

Run `nx test api` to execute the unit tests.
22 changes: 22 additions & 0 deletions libs/blog-bff/pages/api/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/* eslint-disable */
export default {
displayName: 'api',
preset: '../../../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
coverageDirectory: '../../../../coverage/libs/blog-bff/pages/api',
transform: {
'^.+\\.(ts|mjs|js|html)$': [
'jest-preset-angular',
{
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
},
],
},
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
],
};
20 changes: 20 additions & 0 deletions libs/blog-bff/pages/api/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "api-pages",
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/blog-bff/pages/api/src",
"prefix": "al",
"projectType": "library",
"tags": ["scope:bff", "type:api"],
"targets": {
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "libs/blog-bff/pages/api/jest.config.ts"
}
},
"lint": {
"executor": "@nx/eslint:lint"
}
}
}
1 change: 1 addition & 0 deletions libs/blog-bff/pages/api/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as pages } from './lib/api';
35 changes: 35 additions & 0 deletions libs/blog-bff/pages/api/src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Hono } from 'hono';

import {
appCache,
langMw,
} from '@angular-love/blog-bff/shared/util-middleware';
import { ArrayResponse } from '@angular-love/blog-contracts/shared';
import { Page } from '@angular-love/blog/contracts/pages';
import { wpClientMw } from '@angular-love/util-wp';

import { toPage, toPageList } from './mappers';
import { WpPages } from './wp-pages';

const app = new Hono().use(appCache).use(wpClientMw).use(langMw());

app.get('/', async (c) => {
const client = new WpPages(c.var.createWPClient());

const result = await client.getPages();

return c.json(<ArrayResponse<Page>>{
data: toPageList(result.data),
total: Number(result.headers.get('x-wp-total')),
});
});

app.get('/:slug', async (c) => {
const slug = c.req.param('slug');
const client = new WpPages(c.var.createWPClient());
const result = await client.getBySlug(slug);

return c.json(toPage(result.data[0]));
});

export default app;
17 changes: 17 additions & 0 deletions libs/blog-bff/pages/api/src/lib/dtos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export interface WPPageDto {
slug: string;
title: {
rendered: string;
};
content: {
rendered: string;
};
excerpt: {
rendered: string;
};
other_translations: {
locale: string;
slug: string;
}[];
lang: string;
}
27 changes: 27 additions & 0 deletions libs/blog-bff/pages/api/src/lib/mappers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Page } from '@angular-love/blog/contracts/pages';

import { WPPageDto } from './dtos';

export const toPageList = (dto: WPPageDto[]): Page[] => {
return (dto || []).map((dto) => {
return {
slug: dto.slug,
title: dto.title.rendered,
content: dto.content.rendered,
excerpt: dto.excerpt.rendered,
otherTranslations: dto.other_translations || [],
lang: dto.lang.slice(0, 2),
};
});
};

export const toPage = (dto: WPPageDto): Page => {
return {
slug: dto.slug,
title: dto.title.rendered,
content: dto.content.rendered,
excerpt: dto.excerpt.rendered,
otherTranslations: dto.other_translations || [],
lang: dto.lang.slice(0, 2),
};
};
15 changes: 15 additions & 0 deletions libs/blog-bff/pages/api/src/lib/wp-pages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { WPResponse, WPRestClient } from '@angular-love/util-wp';

import { WPPageDto } from './dtos';

export class WpPages {
constructor(private readonly _wpClient: WPRestClient) {}

getPages(): Promise<WPResponse<WPPageDto[]>> {
return this._wpClient.get<WPPageDto[]>('pages', {});
}

getBySlug(slug: string): Promise<WPResponse<WPPageDto[]>> {
return this._wpClient.get('pages', { slug: slug });
}
}
9 changes: 9 additions & 0 deletions libs/blog-bff/pages/api/src/test-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import 'jest-preset-angular/setup-jest';

// @ts-expect-error https://thymikee.github.io/jest-preset-angular/docs/getting-started/test-environment
globalThis.ngJest = {
testEnvironmentOptions: {
errorOnUnknownElements: true,
errorOnUnknownProperties: true,
},
};
28 changes: 28 additions & 0 deletions libs/blog-bff/pages/api/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"target": "es2022",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
],
"extends": "../../../../tsconfig.base.json",
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
17 changes: 17 additions & 0 deletions libs/blog-bff/pages/api/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../../dist/out-tsc",
"declaration": true,
"declarationMap": true,
"inlineSources": true,
"types": []
},
"exclude": [
"src/**/*.spec.ts",
"src/test-setup.ts",
"jest.config.ts",
"src/**/*.test.ts"
],
"include": ["src/**/*.ts"]
}
16 changes: 16 additions & 0 deletions libs/blog-bff/pages/api/tsconfig.spec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../../dist/out-tsc",
"module": "commonjs",
"target": "es2016",
"types": ["jest", "node"]
},
"files": ["src/test-setup.ts"],
"include": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
Loading