Skip to content

Commit

Permalink
chore: use honojs for api (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
Din authored Jan 24, 2024
1 parent cf1d138 commit c6fc249
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 60 deletions.
103 changes: 44 additions & 59 deletions @api/core/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,76 +7,61 @@
*
* Learn more at https://developers.cloudflare.com/workers/
*/
import * as _A from '../node_modules/hono/dist/types/context'
import { appRouter } from './router'
import { handleWebhookRequest } from '@api/features/billing/webhook'
import type { Context } from '@api/lib/context'
import { createContext } from '@api/lib/context'
import { envSchema } from '@api/lib/env'
import { type Env, envSchema } from '@api/lib/env'
import { fetchRequestHandler } from '@trpc/server/adapters/fetch'
import { Hono } from 'hono'
import { cors } from 'hono/cors'

export default {
async fetch(request: Request, unvalidatedEnv: unknown, ec: ExecutionContext) {
const env = envSchema.parse(unvalidatedEnv)
const context = createContext({ env, ec })
const url = new URL(request.url)

let response: Response | undefined

if (request.method === 'OPTIONS') response = new Response()

if (!response && url.pathname.startsWith('/trpc')) {
response = await fetchRequestHandler({
endpoint: '/trpc',
req: request,
router: appRouter,
createContext: () => ({ ...context, request }),
onError({ error }) {
if (error.code === 'INTERNAL_SERVER_ERROR') console.error(error)
},
})
}

if (!response && url.pathname.startsWith('/billing/webhook') && request.method === 'POST') {
response = await handleWebhookRequest({ ...context, request })
}
type Variables = {
context: Context
}

if (!response && url.pathname.startsWith('/public') && request.method.toUpperCase() === 'GET') {
const objectName = url.pathname.replace('/public/', '')
const object = await env.PUBLIC_BUCKET.get(objectName)
const app = new Hono<{ Variables: Variables; Bindings: Env }>()
.use('*', cors())
.use('*', async (c, next) => {
// VALIDATE ENV FOR ENSURE
const env = envSchema.parse(c.env)
const context = createContext({ env, ec: c.executionCtx })

if (object) {
const headers = new Headers()
object.writeHttpMetadata(headers)
headers.set('etag', object.httpEtag)
c.set('context', context)

return new Response(object.body, {
headers,
})
}
}
await next()

response ??= new Response(
JSON.stringify({
message: 'Not found',
}),
{
status: 404,
headers: {
'Content-Type': 'application/json',
},
c.executionCtx.waitUntil(context.ph.shutdownAsync())
})
.all('/trpc/*', async (c) => {
return await fetchRequestHandler({
endpoint: '/trpc',
req: c.req.raw,
router: appRouter,
createContext: () => ({ ...c.get('context'), request: c.req.raw }),
onError({ error }) {
if (error.code === 'INTERNAL_SERVER_ERROR') console.error(error)
},
)
})
})
.post('/billing/webhook', async (c) => {
return await handleWebhookRequest({ ...c.get('context'), request: c.req.raw })
})
.get('/public/:objectName{.+}', async (c) => {
const object = await c.env.PUBLIC_BUCKET.get(c.req.param('objectName'))

try {
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Methods', '*')
response.headers.set('Access-Control-Allow-Headers', '*')
response.headers.set('Access-Control-Max-Age', '86400')
} catch (e) {
/* empty */
}
if (object) {
const headers = new Headers()
object.writeHttpMetadata(headers)
headers.set('etag', object.httpEtag)

ec.waitUntil(context.ph.shutdownAsync())
return new Response(object.body, {
headers,
})
}
})

return response
},
export default {
fetch: app.fetch,
}
1 change: 1 addition & 0 deletions @api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"arctic": "^0.3.6",
"drizzle-orm": "^0.29.3",
"drizzle-zod": "^0.5.1",
"hono": "^3.12.6",
"jose": "^5.2.0",
"oslo": "^0.23.5",
"postgres": "^3.4.3",
Expand Down
2 changes: 1 addition & 1 deletion @extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"dev": "env-cmd -f ../@web/.env.local vite",
"dev:extension": "pnpm run dev",
"build": "tsc --build && tsc-alias",
"typecheck": "tsc --noEmit",
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit c6fc249

Please sign in to comment.