From cf4c065ecc9c4370eead7b9c624aedfced30b457 Mon Sep 17 00:00:00 2001 From: Lucky3028 Date: Wed, 30 Aug 2023 23:34:03 +0900 Subject: [PATCH] feat: use sentry for fetch fun --- apps/auto-run-ac/src/handlers/fetch.ts | 38 ++++++++++++++++++-------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/apps/auto-run-ac/src/handlers/fetch.ts b/apps/auto-run-ac/src/handlers/fetch.ts index 9ac574c..13f00cc 100644 --- a/apps/auto-run-ac/src/handlers/fetch.ts +++ b/apps/auto-run-ac/src/handlers/fetch.ts @@ -7,6 +7,7 @@ import { basicAuth } from 'hono/basic-auth'; import { serveStatic } from 'hono/cloudflare-workers'; import * as build from 'switchbot-web/build'; import __STATIC_CONTENT_MANIFEST from '__STATIC_CONTENT_MANIFEST'; +import { initSentry, isProduction } from 'shared'; const assetManifest = JSON.parse(__STATIC_CONTENT_MANIFEST); let handleRemixRequest: ReturnType; @@ -16,27 +17,38 @@ type ContextEnv = { }; const api = new Hono(); +// ヘルスチェック用エンドポイント +api.get('/', (c) => c.text('Hello!')); export const app = new Hono(); + +// ミドルウェア app.use('*', logger()); +// favicon app.get('/favicon.ico', serveStatic({ path: './favicon.ico' })); +// ミドルウェア app.use('*', (c, next) => basicAuth({ username: c.env.BASIC_AUTH_USER, password: c.env.BASIC_AUTH_PASSWORD })(c, next)); -app.route('/api', api); -app.get('*', async (context) => { +// API +app.route('/api/*', api); +// Remix +app.get('*', async (ctx) => { + const sentry = initSentry(ctx.env.SENTRY_DSN, ctx.env.SENTRY_CLIENT_ID, ctx.env.SENTRY_CLIENT_SECRET, ctx.executionCtx); + const isProd = isProduction(ctx.env.NODE_ENV); + try { - const url = new URL(context.req.url); + const url = new URL(ctx.req.url); const ttl = url.pathname.startsWith('/build/') ? 60 * 60 * 24 * 365 // 1 year : 60 * 5; // 5 minutes return await getAssetFromKV( { - request: context.req.raw, - waitUntil: (promise) => context.executionCtx.waitUntil(promise), + request: ctx.req.raw, + waitUntil: (promise) => ctx.executionCtx.waitUntil(promise), }, { // eslint-disable-next-line no-underscore-dangle - ASSET_NAMESPACE: context.env.__STATIC_CONTENT, + ASSET_NAMESPACE: ctx.env.__STATIC_CONTENT, ASSET_MANIFEST: assetManifest, cacheControl: { browserTTL: ttl, @@ -45,18 +57,22 @@ app.get('*', async (context) => { }, ); } catch (error) { - console.error(error); + if (isProd) { + sentry.captureException(error); + } } try { if (!handleRemixRequest) { - handleRemixRequest = createRequestHandler(build, context.env.NODE_ENV); + handleRemixRequest = createRequestHandler(build, ctx.env.NODE_ENV); } - const loadContext: AppLoadContext = { env: context.env }; + const loadContext: AppLoadContext = { env: ctx.env }; - return await handleRemixRequest(context.req.raw, loadContext); + return await handleRemixRequest(ctx.req.raw, loadContext); } catch (error) { - console.log(error); + if (isProd) { + sentry.captureException(error); + } return new Response('An unexpected error occurred', { status: 500 }); }