|
| 1 | +import { serve } from '@hono/node-server' |
| 2 | +import { Hono } from 'hono' |
| 3 | +import { z } from 'zod' |
| 4 | +import { zValidator } from '@hono/zod-validator' |
| 5 | +import { createClient } from './supabase/client.ts' |
| 6 | +import { HTTPException } from 'hono/http-exception' |
| 7 | +import { deployOnSupabase } from './supabase/deploy.ts' |
| 8 | + |
| 9 | +const app = new Hono() |
| 10 | + |
| 11 | +app.get( |
| 12 | + '/', |
| 13 | + zValidator( |
| 14 | + 'json', |
| 15 | + z.object({ |
| 16 | + databaseId: z.string(), |
| 17 | + integrationId: z.string(), |
| 18 | + databaseUrl: z.string(), |
| 19 | + }) |
| 20 | + ), |
| 21 | + async (c) => { |
| 22 | + const { databaseId, integrationId, databaseUrl: localDatabaseUrl } = c.req.valid('json') |
| 23 | + |
| 24 | + const token = c.req.header('Authorization')?.replace('Bearer ', '') |
| 25 | + |
| 26 | + if (!token) { |
| 27 | + throw new HTTPException(401, { message: 'Unauthorized' }) |
| 28 | + } |
| 29 | + |
| 30 | + const supabase = createClient() |
| 31 | + |
| 32 | + const { error } = await supabase.auth.getUser(token) |
| 33 | + |
| 34 | + if (error) { |
| 35 | + throw new HTTPException(401, { message: 'Unauthorized' }) |
| 36 | + } |
| 37 | + |
| 38 | + // TODO: create a lock in postgres to prevent multiple deployments |
| 39 | + // await supabase.from('deployment_locks').insert({ |
| 40 | + // local_database_id: databaseId, |
| 41 | + // }) |
| 42 | + try { |
| 43 | + const { databaseUrl } = await deployOnSupabase( |
| 44 | + { supabase }, |
| 45 | + { databaseId, integrationId, localDatabaseUrl } |
| 46 | + ) |
| 47 | + return c.json({ databaseUrl }) |
| 48 | + } catch (error: unknown) { |
| 49 | + if (error instanceof Error) { |
| 50 | + throw new HTTPException(500, { message: error.message }) |
| 51 | + } |
| 52 | + throw new HTTPException(500, { message: 'Internal server error' }) |
| 53 | + } finally { |
| 54 | + // TODO: remove the lock |
| 55 | + // await supabase.from('deployment_locks').delete().eq('local_database_id', databaseId) |
| 56 | + } |
| 57 | + } |
| 58 | +) |
| 59 | + |
| 60 | +const port = 4000 |
| 61 | +console.log(`Server is running on port ${port}`) |
| 62 | + |
| 63 | +serve({ |
| 64 | + fetch: app.fetch, |
| 65 | + port, |
| 66 | +}) |
0 commit comments