Skip to content

Commit

Permalink
feat: use sentry for fetch fun
Browse files Browse the repository at this point in the history
  • Loading branch information
Lucky3028 committed Aug 30, 2023
1 parent c2b3b3b commit cf4c065
Showing 1 changed file with 27 additions and 11 deletions.
38 changes: 27 additions & 11 deletions apps/auto-run-ac/src/handlers/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof createRequestHandler>;
Expand All @@ -16,27 +17,38 @@ type ContextEnv = {
};

const api = new Hono<ContextEnv>();
// ヘルスチェック用エンドポイント
api.get('/', (c) => c.text('Hello!'));

export const app = new Hono<ContextEnv>();

// ミドルウェア
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,
Expand All @@ -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 });
}
Expand Down

0 comments on commit cf4c065

Please sign in to comment.