Skip to content

[refactor] make GitHub & Lark API clearer & safer with Koa 2 & Next-SSR-middleware 0.10 #77

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 2 commits into from
May 4, 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
2 changes: 2 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
public-hoist-pattern[] = *import-in-the-middle*
public-hoist-pattern[] = *require-in-the-middle*
auto-install-peers = false
4 changes: 2 additions & 2 deletions components/Client/Partner.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Tooltip } from '@mui/material';
import { FC, ReactNode } from 'react';

import { fileURLOf } from '../../models/Base';
import { Client } from '../../models/Client';
import { fileURLOf } from '../../pages/api/Lark/file/[id]';
import { LarkImage } from '../LarkImage';

export interface PartnerProps extends Client {
Expand Down Expand Up @@ -41,7 +41,7 @@ export const LogoWithLink: FC<Omit<PartnerOverviewProps, 'tooltip'>> = ({
address,
logo,
logoDark,
className
className,
}) => (
<a
key={name}
Expand Down
12 changes: 5 additions & 7 deletions components/Icon.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { FC, HTMLAttributes, PropsWithRef } from 'react';
import { FC, HTMLAttributes } from 'react';

export type IconProps = PropsWithRef<
HTMLAttributes<HTMLSpanElement> & {
name: string;
variant?: 'outlined' | 'rounded' | 'sharp';
}
>;
export interface IconProps extends HTMLAttributes<HTMLSpanElement> {
name: string;
variant?: 'outlined' | 'rounded' | 'sharp';
}

export const SymbolIcon: FC<IconProps> = ({ className, name, variant = 'outlined', ...props }) => (
<span
Expand Down
3 changes: 2 additions & 1 deletion components/LarkImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { TableCellValue } from 'mobx-lark';
import { ImageProps } from 'next/image';
import { FC } from 'react';

import { DefaultImage, fileURLOf } from '../pages/api/Lark/file/[id]';
import { fileURLOf } from '../models/Base';
import { DefaultImage } from '../models/configuration';

export interface LarkImageProps extends Omit<ImageProps, 'src'> {
src?: TableCellValue;
Expand Down
5 changes: 2 additions & 3 deletions components/PageHead.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import Head from 'next/head';
import type { FC, PropsWithChildren } from 'react';

import { Name, Summary } from '../models/configuration';

export type PageHeadProps = PropsWithChildren<{
title?: string;
description?: string;
}>;

const Name = process.env.NEXT_PUBLIC_SITE_NAME,
Summary = process.env.NEXT_PUBLIC_SITE_SUMMARY;

export const PageHead: FC<PageHeadProps> = ({ title, description = Summary, children }) => (
<Head>
<title>{(title ? `${title} - ` : '') + Name}</title>
Expand Down
File renamed without changes.
7 changes: 7 additions & 0 deletions instrumentation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const { NEXT_RUNTIME } = process.env;

export async function register() {
if (NEXT_RUNTIME === 'nodejs') await import('./sentry.server.config');

if (NEXT_RUNTIME === 'edge') await import('./sentry.edge.config');
}
25 changes: 15 additions & 10 deletions models/Base.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import { HTTPClient } from 'koajax';
import MIME from 'mime';
import { TableCellValue, TableCellMedia, TableCellAttachment } from 'mobx-lark';

export const isServer = () => typeof window === 'undefined';

export const VercelHost = process.env.VERCEL_URL,
LarkBaseId = process.env.NEXT_PUBLIC_LARK_BASE!;

export const API_Host = isServer()
? VercelHost
? `https://${VercelHost}`
: 'http://localhost:3000'
: globalThis.location.origin;
import { API_Host } from './configuration';

export const larkClient = new HTTPClient({
baseURI: `${API_Host}/api/Lark/`,
responseType: 'json',
});

export function fileURLOf(field: TableCellValue, cache = false) {
if (!(field instanceof Array) || !field[0]) return field + '';

const file = field[0] as TableCellMedia | TableCellAttachment;

let URI = `/api/Lark/file/${'file_token' in file ? file.file_token : file.attachmentToken}`;

if (cache) URI += '.' + MIME.getExtension('type' in file ? file.type : file.mimeType);

return URI;
}
3 changes: 2 additions & 1 deletion models/Client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BiDataQueryOptions, BiDataTable, TableCellValue } from 'mobx-lark';

import { LarkBaseId, larkClient } from './Base';
import { larkClient } from './Base';
import { LarkBaseId } from './configuration';

export type Client = Record<
'id' | 'name' | 'type' | 'partnership' | 'image' | 'summary' | 'address',
Expand Down
3 changes: 2 additions & 1 deletion models/Member.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BiDataQueryOptions, BiDataTable, TableCellValue } from 'mobx-lark';

import { LarkBaseId, larkClient } from './Base';
import { larkClient } from './Base';
import { LarkBaseId } from './configuration';

export type Member = Record<
'id' | 'nickname' | 'type' | 'skill' | 'position' | 'summary' | 'github' | 'joinedAt',
Expand Down
11 changes: 6 additions & 5 deletions models/Project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import {
normalizeText,
TableCellLink,
TableCellValue,
TableRecord
TableRecord,
} from 'mobx-lark';
import { NewData } from 'mobx-restful';
import { isEmpty } from 'web-utility';

import { LarkBaseId, larkClient } from './Base';
import { larkClient } from './Base';
import { LarkBaseId } from './configuration';

export type Project = Record<
| 'id'
Expand Down Expand Up @@ -45,17 +46,17 @@ export class ProjectModel extends BiDataTable<Project>() {
makeFilter(filter: NewData<Project>) {
return [
'NOT(CurrentValue.[settlementDate]="")',
isEmpty(filter) ? undefined : makeSimpleFilter(filter)
isEmpty(filter) ? undefined : makeSimpleFilter(filter),
]
.filter(Boolean)
.join('&&');
}

normalize({ id, fields: { link, ...fields } }: TableRecord<Project>) {
extractFields({ id, fields: { link, ...fields } }: TableRecord<Project>) {
return {
...fields,
id,
link: link && normalizeText(link as TableCellLink)
link: link && normalizeText(link as TableCellLink),
};
}
}
Expand Down
10 changes: 3 additions & 7 deletions models/Repository.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
import { observable } from 'mobx';
import { githubClient, GitRepository, RepositoryFilter, RepositoryModel } from 'mobx-github';
import { parseCookie } from 'mobx-i18n';
import { Stream } from 'mobx-restful';

import { API_Host, isServer } from './Base';

const GithubToken =
parseCookie(globalThis.document?.cookie || '').token || process.env.GITHUB_TOKEN;
import { API_Host, GithubToken, isServer } from './configuration';

if (!isServer()) githubClient.baseURI = `${API_Host}/api/GitHub/`;

githubClient.use(({ request }, next) => {
if (GithubToken)
request.headers = {
authorization: `Bearer ${GithubToken}`,
...request.headers
...request.headers,
};
return next();
});
Expand Down Expand Up @@ -42,7 +38,7 @@ export class GitRepositoryModel extends Stream<GitRepository, RepositoryFilter>(
const { pageData, totalCount } = await loadPage.call(this, i, this.pageSize, filter);
const list = pageData.filter(
({ description, topics, fork, archived }) =>
description?.trim() && topics?.[0] && !fork && !archived
description?.trim() && topics?.[0] && !fork && !archived,
);
const droppedCount = pageData.length - list.length;

Expand Down
30 changes: 30 additions & 0 deletions models/configuration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { parseCookie } from 'mobx-i18n';

export const Name = process.env.NEXT_PUBLIC_SITE_NAME,
Summary = process.env.NEXT_PUBLIC_SITE_SUMMARY,
DefaultImage = process.env.NEXT_PUBLIC_LOGO || '/og.png';

export const isServer = () => typeof window === 'undefined';

export const VercelHost = process.env.VERCEL_URL;

export const API_Host = isServer()
? VercelHost
? `https://${VercelHost}`
: 'http://localhost:3000'
: globalThis.location.origin;

export const CACHE_HOST = process.env.NEXT_PUBLIC_CACHE_HOST!;

export const { CRAWLER_TOKEN, JWT_SECRET } = process.env;

export const GithubToken =
parseCookie(globalThis.document?.cookie || '').token || process.env.GITHUB_TOKEN;

export const LARK_API_HOST = `${API_Host}/api/Lark/`;

export const LarkAppMeta = {
id: process.env.LARK_APP_ID!,
secret: process.env.LARK_APP_SECRET!,
};
export const LarkBaseId = process.env.NEXT_PUBLIC_LARK_BASE!;
76 changes: 46 additions & 30 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,62 +10,78 @@
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0",
"@giscus/react": "^3.1.0",
"@koa/bodyparser": "^5.1.1",
"@koa/router": "^13.1.0",
"@mui/lab": "6.0.0-beta.31",
"@mui/material": "^6.4.8",
"@sentry/nextjs": "^9.6.0",
"file-type": "^20.4.1",
"koajax": "^3.1.1",
"@mui/material": "^6.4.11",
"@sentry/nextjs": "^9.15.0",
"file-type": "^20.5.0",
"jsonwebtoken": "^9.0.2",
"koa": "^2.16.1",
"koa-jwt": "^4.0.4",
"koajax": "^3.1.2",
"lodash": "^4.17.21",
"marked": "^15.0.7",
"mime": "^4.0.6",
"marked": "^15.0.11",
"mime": "^4.0.7",
"mobx": "^6.13.7",
"mobx-github": "^0.3.5",
"mobx-i18n": "^0.6.0",
"mobx-lark": "^2.1.0",
"mobx-lark": "^2.2.0",
"mobx-react": "^9.2.0",
"mobx-restful": "^2.1.0",
"next": "^15.2.3",
"next": "^15.3.1",
"next-pwa": "~5.6.0",
"next-ssr-middleware": "^0.8.10",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"next-ssr-middleware": "^0.10.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"web-utility": "^4.4.3",
"webpack": "^5.98.0"
"webpack": "^5.99.7"
},
"devDependencies": {
"@babel/plugin-proposal-decorators": "^7.25.9",
"@babel/plugin-transform-typescript": "^7.26.8",
"@babel/preset-react": "^7.26.3",
"@cspell/eslint-plugin": "^8.17.5",
"@eslint/compat": "^1.2.7",
"@eslint/js": "^9.22.0",
"@next/eslint-plugin-next": "^15.2.3",
"@babel/plugin-proposal-decorators": "^7.27.1",
"@babel/plugin-transform-typescript": "^7.27.1",
"@babel/preset-react": "^7.27.1",
"@cspell/eslint-plugin": "^8.19.4",
"@eslint/compat": "^1.2.9",
"@eslint/js": "^9.26.0",
"@next/eslint-plugin-next": "^15.3.1",
"@stylistic/eslint-plugin": "^4.2.0",
"@tailwindcss/postcss": "^4.0.14",
"@tailwindcss/postcss": "^4.1.5",
"@types/eslint-config-prettier": "^6.11.3",
"@types/jsonwebtoken": "^9.0.9",
"@types/koa": "^2.15.0",
"@types/koa__router": "^12.0.4",
"@types/lodash": "^4.17.16",
"@types/next-pwa": "^5.6.9",
"@types/node": "^22.13.10",
"@types/react": "^19.0.11",
"eslint": "^9.22.0",
"eslint-config-next": "^15.2.3",
"eslint-config-prettier": "^10.1.1",
"eslint-plugin-react": "^7.37.4",
"@types/node": "^22.15.3",
"@types/react": "^19.1.2",
"eslint": "^9.26.0",
"eslint-config-next": "^15.3.1",
"eslint-config-prettier": "^10.1.2",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-simple-import-sort": "^12.1.1",
"globals": "^16.0.0",
"husky": "^9.1.7",
"lint-staged": "^15.5.0",
"jiti": "^2.4.2",
"lint-staged": "^15.5.1",
"postcss": "^8.5.3",
"prettier": "^3.5.3",
"prettier-plugin-css-order": "^2.1.2",
"prettier-plugin-tailwindcss": "^0.6.11",
"tailwindcss": "^4.0.14",
"typescript": "~5.8.2",
"typescript-eslint": "^8.26.1"
"tailwindcss": "^4.1.5",
"typescript": "~5.8.3",
"typescript-eslint": "^8.31.1"
},
"resolutions": {
"next": "$next"
},
"pnpm": {
"onlyBuiltDependencies": [
"@sentry/cli",
"sharp",
"unrs-resolver"
]
},
"prettier": {
"singleQuote": true,
"trailingComma": "all",
Expand Down
2 changes: 1 addition & 1 deletion pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Head from 'next/head';

import { Footer } from '../components/Layout/Footer';
import { MainNavigator } from '../components/Layout/MainNavigator';
import { isServer } from '../models/Base';
import { isServer } from '../models/configuration';

configure({ enforceActions: 'never' });

Expand Down
2 changes: 1 addition & 1 deletion pages/_document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import InitColorSchemeScript from '@mui/material/InitColorSchemeScript';
import { Head, Html, Main, NextScript } from 'next/document';
import Script from 'next/script';

import { DefaultImage } from './api/Lark/file/[id]';
import { DefaultImage } from '../models/configuration';

/**
* Influence Google Search to display search results with the name "idea2app" instead of idea2.app
Expand Down
13 changes: 11 additions & 2 deletions pages/api/GitHub/[...slug].ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
import { proxyGithub } from './core';
import { createKoaRouter } from 'next-ssr-middleware';

export default proxyGithub();
import { withSafeKoaRouter } from '../core';
import { proxyGitHubAll } from './core';

export const config = { api: { bodyParser: false } };

const router = createKoaRouter(import.meta.url);

router.get('/(.*)', proxyGitHubAll);

export default withSafeKoaRouter(router);
Loading