import { serve } from '@hono/node-server'
import type { AppType as HookfishAppType } from '@hookfish/api'
import { HookfishServer } from '@hookfish/api'
import { Hono } from 'hono'
import { hc } from 'hono/client'
import config from '../hookfish.config'
import { requireUser } from './auth'
import { scopedBrokerTokenFor } from './broker-tokens'
const hookfish = await HookfishServer.init(config)
const app = new Hono()
const applicationUrl =
process.env.APPLICATION_URL ?? 'http://127.0.0.1:3000'
function hookfishFor(brokerToken: string) {
return hc<HookfishAppType>(`${applicationUrl}/api`, {
headers: {
Authorization: `Bearer ${brokerToken}`,
},
fetch: (input, init) =>
hookfish.fetch(new Request(input, init), process.env),
})
}
const applicationRoutes = app
.get('/rpc/integrations/connections', requireUser, async (context) => {
const user = context.get('user')
const brokerToken = await scopedBrokerTokenFor(user.organizationId)
const hookfishClient = hookfishFor(brokerToken)
const response = await hookfishClient.oauth.connections.$get({
query: {
connection_id_prefix: user.organizationId,
},
})
if (!response.ok) {
return context.json({ error: 'Could not load connections.' }, 502)
}
return context.json(await response.json())
})
app.all('/api/*', (context) => hookfish.fetch(context.req.raw, process.env))
serve({
fetch: app.fetch,
hostname: process.env.HOST ?? '127.0.0.1',
port: Number(process.env.PORT ?? 3000),
})
export type ApplicationApi = typeof applicationRoutes