Skip to content

Commit

Permalink
Merge pull request #185 from n0th1ng-else/articles
Browse files Browse the repository at this point in the history
  • Loading branch information
n0th1ng-else authored Mar 20, 2022
2 parents f22fb6f + 419db2d commit 06b601f
Show file tree
Hide file tree
Showing 12 changed files with 64 additions and 19 deletions.
3 changes: 3 additions & 0 deletions articles/2022/test.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ title: This is a test
description: Once upon a time...
language: en
published: 2022-03-19
keywords:
- test
- test2
draft: true
---

Expand Down
1 change: 1 addition & 0 deletions common.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface LinkInfo {
logo?: string;
content?: string;
internal?: boolean;
keywords?: string[];
}

export interface MetaInfo {
Expand Down
2 changes: 1 addition & 1 deletion env.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const distInRoot = Boolean(process.env.DIST_ROOT) || false;

const mode = process.env.NODE_ENV || 'development';

const selfUrl = process.env.SELF_URL || '';
const selfUrl = process.env.SELF_URL || 'localhost:3000';

const versionBuild = process.env.COMMIT_HASH || process.env.VERCEL_GIT_COMMIT_SHA || '';

Expand Down
9 changes: 7 additions & 2 deletions src/helpers/api.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { CloudinaryPayload } from './cloudinary';
import type { SignatureResponse, Version } from '../types/api';
import type { MetaInfo, LinkInfo, ProfileAccounts } from '../../common';
import type { WithPagination } from '../types/api';

const runApi = <Req = unknown, Res = unknown>(
url: string,
Expand All @@ -22,6 +23,10 @@ const runApi = <Req = unknown, Res = unknown>(

const getApiPath = (path: string, pageUrl?: string): string => {
const url = pageUrl ? `${pageUrl}/api/v1/${path}` : `/api/v1/${path}`;
return getUrlPrefix(url);
};

export const getUrlPrefix = (url: string): string => {
if (url.startsWith('http')) {
return url;
}
Expand All @@ -33,7 +38,7 @@ const withQuery = (url: string, params: Record<string, unknown>): string => {
.filter(key => params[key])
.map(key => `${key}=${params[key]}`)
.join('&');
return `${url}?${q}`;
return q ? `${url}?${q}` : url;
};

// Browser API ----------------------------------------------------------------
Expand Down Expand Up @@ -73,7 +78,7 @@ export const getProfile = (host: string): Promise<MetaInfo> => runApi(getApiPath
export const getPackages = (host: string): Promise<LinkInfo[]> =>
runApi(getApiPath('packages', host));

export const getArticles = (host: string, draft?: boolean): Promise<LinkInfo[]> =>
export const getArticles = (host: string, draft?: boolean): Promise<WithPagination<LinkInfo>> =>
runApi(withQuery(getApiPath(`articles`, host), { draft }));

export const getArticle = (host: string, slug: string, draft?: boolean): Promise<LinkInfo> =>
Expand Down
2 changes: 2 additions & 0 deletions src/helpers/selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ export const getVersion = (): string => runtime.env.version ?? '';
export const getVersionBuild = (): string => runtime.env.versionBuild ?? '';

export const isProduction = (): boolean => runtime.env.mode === 'production';

export const getSelfUrl = (): string => runtime.env.selfUrl;
11 changes: 8 additions & 3 deletions src/helpers/server/articles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ import { Logger } from '../log';
const logger = new Logger('articles:server');

interface InternalMetadata {
title: string;
description: string;
language: ArticleLanguage;
published: string;
description: string;
title: string;
keywords: string[];
draft?: boolean;
}

Expand Down Expand Up @@ -65,7 +66,6 @@ const parseArticle = (
try {
const fileContents = readFileSync(file, 'utf8');
const { content, metadata } = parseMD(fileContents);
const articleContent = withContent ? { content } : {};

if (!isMetadata(metadata)) {
return null;
Expand All @@ -76,8 +76,13 @@ const parseArticle = (
return null;
}

const articleContent = withContent ? { content } : {};
const keywords =
metadata.keywords && Array.isArray(metadata.keywords) ? { keywords: metadata.keywords } : {};

return {
...articleContent,
...keywords,
id: slug,
service: 'blog',
url: slug,
Expand Down
6 changes: 4 additions & 2 deletions src/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import type { Handle } from '@sveltejs/kit';
import { initUptime } from './helpers/uptime';
import { isProduction } from './helpers/selectors';
import { getSelfUrl, isProduction } from './helpers/selectors';
import { getUrlPrefix } from './helpers/api';

export const handle: Handle<void, void> = ({ request, resolve }) => {
if (isProduction()) {
initUptime(request.host);
const url = getUrlPrefix(getSelfUrl());
initUptime(url);
}

return resolve(request);
Expand Down
5 changes: 3 additions & 2 deletions src/routes/api/v1/articles/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import type { RequestHandler } from '@sveltejs/kit';

import type { LinkInfo } from '../../../../../common';
import { getArticles } from '../../../../helpers/selectors';
import { getInternalArticles } from '../../../../helpers/server/articles';
import type { LinkInfo } from '../../../../../common';
import type { WithPagination } from '../../../../types/api';

// @ts-expect-error finite interface CAN NOT have index signature
export const get: RequestHandler<void, void, LinkInfo[]> = ({ query }) => {
export const get: RequestHandler<void, void, WithPagination<LinkInfo>> = ({ query }) => {
try {
const showDraft = query.get('draft') === 'true';
const items = [...getArticles(), ...getInternalArticles(showDraft)];
Expand Down
34 changes: 26 additions & 8 deletions src/routes/blog/index.svelte
Original file line number Diff line number Diff line change
@@ -1,15 +1,32 @@
<script lang="ts" context="module">
import type { Load } from '@sveltejs/kit';
import { getArticles } from '../../helpers/api';
import { Logger } from '../../helpers/log';
export const load: Load = ({ page }) => {
const logger = new Logger('articles:ssr');
export const load: Load = async ({ page }) => {
const host = page.host;
const path = page.path;
const pageUrl = `${host}${path}`;
return {
props: {
pageUrl: `${host}${path}`
}
};
try {
const articles = await getArticles(host);
return {
props: {
articles: articles.items,
pageUrl
}
};
} catch (err) {
logger.error('Failed to load an articles', err);
return {
props: {
articles: [],
pageUrl
}
};
}
};
</script>

Expand All @@ -22,16 +39,17 @@
import Paragraph from '../../ui/Paragraph.svelte';
import { toArticle } from '../../helpers/routes';
import { blogTitle as title } from '../../labels';
import { getArticles, getProfile } from '../../helpers/selectors';
import { getProfile } from '../../helpers/selectors';
import { groupByYear, getRelativeDate, sortByDate } from '../../helpers/date';
import { sortAsNumber } from '../../helpers/sort';
import type { LinkInfo } from '../../../common';
export let articles: LinkInfo[];
export let pageUrl: string;
const photo = getProfile().image ?? '';
const groups = groupByYear(getArticles());
const groups = groupByYear(articles);
const years = sortAsNumber(Object.keys(groups));
const getGroup = (year: string): LinkInfo[] => sortByDate(groups[year]);
Expand Down
7 changes: 7 additions & 0 deletions src/types/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,10 @@ export interface Version {
version: string;
build: string;
}

export interface WithPagination<Item> {
page: number;
pageSize: number;
items: Item[];
total: number;
}
2 changes: 1 addition & 1 deletion svelte.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const config = {
// hydrate the <div id="svelte"> element in src/app.html
target: '#svelte',
appDir: 'generated',
host: env.procEnv.selfUrl || 'localhost:3000',
host: env.procEnv.selfUrl,
adapter: isStatic
? staticAdapter({
pages: 'dist',
Expand Down
1 change: 1 addition & 0 deletions types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ declare global {
accounts: ProfileAccounts;
version: string;
versionBuild: string;
selfUrl: string;
};
profile: MetaInfo;
publications: LinkInfo[];
Expand Down

0 comments on commit 06b601f

Please sign in to comment.