0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Cloudflare Worker で複数ルートの API を実現しつつ、コードサイズも抑えるにはどうすればいいのでしょうか?

0
Posted at

image.png

Worker のデモコードにはルーティング処理が含まれておらず、しかも Free プランでは 1MiB のサイズ制限があるため、コードスペースは非常に貴重です。Serverless アプリケーションとして、Node.js の従来のルーティングライブラリ(例えば @koa/router)のように使いやすいものが欲しいですよね。

私がおすすめするのは「itty-router」です。そのメリットは以下の通りです:

  1. Serverless 向けに設計されている
  2. 非常に小さく、依存関係がゼロ(450+B、530+B、970+B のバージョンあり)
  3. TypeScript に対応
  4. ルート解析やクエリパラメータ解析に対応
  5. ミドルウェアをサポート
  6. 100% のテストカバレッジ

itty-router は Cloudflare Worker だけでなく、Cloudflare Pages にも対応しています:

// Next.js Application
// src/middleware.ts
import createI18nMiddleware from 'next-intl/middleware';
import { createAutoRouter, defineRouteHandler } from './lib/auto-router';
import { routing } from './i18n';
import { NextResponse } from 'next/server';

const i18nMw = defineRouteHandler(createI18nMiddleware(routing));
const i18nWithPathnameMw = defineRouteHandler(async (req, ...rest) => {
  const response = await i18nMw(req, ...rest);
  const pathname = req.nextUrl.pathname;
  response.headers.set('x-pathname', pathname);
  return response;
});

const router = createAutoRouter();
router
  .all('/api/*', async () => {
    return NextResponse.next();
  })
  .all('*', i18nWithPathnameMw)
  ;

export default router.fetch;
export const config = {
  // Match only internationalized pathnames
  matcher: [
    '/((?!_next|_vercel|.*\\..*).*)',
  ],
};
// src/lib/auto-router.ts
import { AutoRouter, StatusError, IttyRouterOptions, IRequest } from 'itty-router';
import { NextRequest } from 'next/server';

type IttyRequest = IRequest & NextRequest;
type IttyRouterHandlerArgs = [IttyRequest];
type IttyRouterHandler = (...args: IttyRouterHandlerArgs) => any | Promise<any>;

export function createAutoRouter(options?: IttyRouterOptions) {
	const router = AutoRouter({
		missing() {
			return new Response('Not found', { status: 404 });
		},
		catch(err: Error) {
			console.error('[catch error]', err);
			if (err instanceof StatusError) {
				return new Response(err.message, { status: err.status });
			}
			if (err instanceof Error) {
				return new Response(err.message, { status: 500 });
			}
			return new Response(`Unexpected error.`, { status: 500 });
		},
		...(options || {}),
	});
	return router;
}

export function defineRouteHandler(fn: IttyRouterHandler) {
	return fn;
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?