Skip to content

πŸš€ QUICK START - Contract API

Heute in 15 Minuten starten!


βœ… Decision: HONO + TypeScript (OHNE SonicJS)

Stack: - βœ… Hono.js (ultrafast web framework) - βœ… TypeScript (type safety) - βœ… Cloudflare D1 (SQLite database) - βœ… Cloudflare KV (cache) - βœ… Drizzle ORM (type-safe queries) - βœ… Zod (validation)

KEIN SonicJS: - ❌ Wir brauchen KEIN CMS - βœ… Pure Business Logic API - βœ… Contract Management, nicht Content Management


πŸ“¦ Method 1: Create Hono (Empfohlen!)

# Navigate to project root
cd /Users/gm/Documents/Visual_Code_SHARED/ContractPlattformWhiteLabel

# Create API directory
mkdir -p api && cd api

# Initialize with Hono template
npm create hono@latest

# Prompts:
# ? Target directory: . (current directory)
# ? Which template do you want to use? cloudflare-workers
# ? Do you want to install project dependencies? yes
# ? Which package manager do you want to use? npm

πŸ“¦ Method 2: Manual Setup

cd /Users/gm/Documents/Visual_Code_SHARED/ContractPlattformWhiteLabel
mkdir -p api && cd api

# Initialize
npm init -y

# Install Hono
npm install hono

# Install Drizzle ORM
npm install drizzle-orm
npm install -D drizzle-kit

# Install Zod
npm install zod

# Install Wrangler
npm install -D wrangler

# TypeScript
npm install -D typescript @types/node
npx tsc --init

πŸ“„ Project Structure

api/
β”œβ”€β”€ package.json
β”œβ”€β”€ tsconfig.json
β”œβ”€β”€ wrangler.toml           ← Cloudflare Config
β”‚
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ index.ts            ← Main Entry
β”‚   β”œβ”€β”€ router.ts           ← Hono Router
β”‚   β”‚
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ contracts.ts    ← POST /v1/contracts
β”‚   β”‚   β”œβ”€β”€ health.ts       ← GET /health
β”‚   β”‚   └── webhooks.ts     ← POST /webhooks/*
β”‚   β”‚
β”‚   β”œβ”€β”€ db/
β”‚   β”‚   β”œβ”€β”€ schema.ts       ← Drizzle Schema
β”‚   β”‚   └── migrations/     ← SQL Migrations
β”‚   β”‚
β”‚   β”œβ”€β”€ validators/
β”‚   β”‚   └── contract.ts     ← Zod Schemas
β”‚   β”‚
β”‚   └── types/
β”‚       β”œβ”€β”€ env.ts          ← Environment Types
β”‚       └── contract.ts     ← Contract Types
β”‚
└── drizzle.config.ts       ← Drizzle Config

πŸ“„ wrangler.toml (Minimal Start)

name = "contractplattform-api"
main = "src/index.ts"
compatibility_date = "2024-01-15"

account_id = "edeaf72f08c3145711f257893d9ddab1"

# D1 Database (erstellen wir gleich)
[[d1_databases]]
binding = "DB"
database_name = "contractplattform-prod"
database_id = ""  # ← Nach 'wrangler d1 create' ausfΓΌllen

# KV Namespace (erstellen wir gleich)
[[kv_namespaces]]
binding = "CACHE"
id = ""  # ← Nach 'wrangler kv:namespace create' ausfΓΌllen

[vars]
ENVIRONMENT = "production"
API_VERSION = "v1"
INSTANCE_ID = "master"

πŸ“ src/index.ts (Minimal)

import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { logger } from 'hono/logger'

type Env = {
  DB: D1Database
  CACHE: KVNamespace
  ENVIRONMENT: string
  API_VERSION: string
  INSTANCE_ID: string
}

const app = new Hono<{ Bindings: Env }>()

// Middleware
app.use('*', cors())
app.use('*', logger())

// Health Check
app.get('/health', (c) => {
  return c.json({
    status: 'ok',
    version: c.env.API_VERSION,
    environment: c.env.ENVIRONMENT,
    instance_id: c.env.INSTANCE_ID,
    timestamp: new Date().toISOString()
  })
})

// Contract API (v1)
app.post('/v1/contracts', async (c) => {
  try {
    const body = await c.req.json()

    // TODO: Zod Validation
    // TODO: Insert in D1
    // TODO: Cache in KV

    return c.json({
      success: true,
      contract_id: 'temp-' + Date.now(),
      message: 'Contract API coming soon!',
      data: body
    }, 201)
  } catch (error) {
    return c.json({
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error'
    }, 500)
  }
})

// 404 Handler
app.notFound((c) => {
  return c.json({
    success: false,
    error: 'Not Found',
    path: c.req.path
  }, 404)
})

// Error Handler
app.onError((err, c) => {
  console.error(err)
  return c.json({
    success: false,
    error: err.message
  }, 500)
})

export default app

πŸ—„οΈ D1 Database erstellen

# Production Database
wrangler d1 create contractplattform-prod

# Output:
# βœ… Successfully created DB 'contractplattform-prod'
# [[d1_databases]]
# binding = "DB"
# database_name = "contractplattform-prod"
# database_id = "abc123-def456-ghi789"  ← KOPIEREN!

# In wrangler.toml eintragen!

Dev Database:

# Local Development Database
wrangler d1 create contractplattform-dev

# Preview Database
wrangler d1 create contractplattform-preview

πŸ’Ύ KV Namespace erstellen

# Production KV
wrangler kv:namespace create CACHE

# Output:
# βœ… Successfully created KV namespace
# [[kv_namespaces]]
# binding = "CACHE"
# id = "xyz123abc456"  ← KOPIEREN!

# In wrangler.toml eintragen!

Dev KV:

# Preview KV
wrangler kv:namespace create CACHE --preview

# Dev KV
wrangler kv:namespace create CACHE --env dev

πŸš€ Development Server

# Starten
npm run dev

# Output:
# ⛅️ wrangler 3.x.x
# ------------------
# [wrangler:inf] Ready on http://localhost:8787

Test Health Check:

curl http://localhost:8787/health

# Response:
{
  "status": "ok",
  "version": "v1",
  "environment": "production",
  "instance_id": "master",
  "timestamp": "2026-01-15T20:30:00.000Z"
}

Test Contract API:

curl -X POST http://localhost:8787/v1/contracts \
  -H "Content-Type: application/json" \
  -d '{
    "instance_id": "morelo",
    "type": "kfz_kaufvertrag",
    "party_a": {"name": "Test Dealer"},
    "party_b": {"name": "Test Customer"}
  }'

# Response:
{
  "success": true,
  "contract_id": "temp-1736968200000",
  "message": "Contract API coming soon!",
  "data": { ... }
}

🌍 Deploy to Cloudflare

# Build & Deploy
npm run deploy

# Output:
# βœ… Uploaded contractplattform-api
# βœ… Published contractplattform-api
# 🌍 https://contractplattform-api.YOUR_SUBDOMAIN.workers.dev

Test Live:

curl https://contractplattform-api.YOUR_SUBDOMAIN.workers.dev/health

βœ… NEXT STEPS (In Order!)

1. Database Schema (Drizzle)

// src/db/schema.ts
import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core'

export const contracts = sqliteTable('contracts', {
  id: text('id').primaryKey(),
  instance_id: text('instance_id').notNull(),
  type: text('type').notNull(),
  status: text('status').notNull().default('draft'),
  party_a: text('party_a', { mode: 'json' }),
  party_b: text('party_b', { mode: 'json' }),
  asset: text('asset', { mode: 'json' }),
  created_at: integer('created_at', { mode: 'timestamp' }),
  updated_at: integer('updated_at', { mode: 'timestamp' })
})

2. Migrations

-- migrations/0001_init.sql
CREATE TABLE IF NOT EXISTS contracts (
  id TEXT PRIMARY KEY,
  instance_id TEXT NOT NULL,
  type TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'draft',
  party_a TEXT,
  party_b TEXT,
  asset TEXT,
  created_at INTEGER,
  updated_at INTEGER
);

CREATE INDEX idx_instance_id ON contracts(instance_id);
CREATE INDEX idx_status ON contracts(status);

3. Apply Migrations

# Local
wrangler d1 migrations apply contractplattform-dev --local

# Production
wrangler d1 migrations apply contractplattform-prod --remote

4. Zod Validation

// src/validators/contract.ts
import { z } from 'zod'

export const contractSchema = z.object({
  instance_id: z.string(),
  type: z.enum(['kfz_kaufvertrag', 'wohnmobil_vertrag', 'yacht_charter']),
  party_a: z.object({
    name: z.string(),
    email: z.string().email().optional()
  }),
  party_b: z.object({
    name: z.string(),
    email: z.string().email().optional()
  })
})

5. Secrets hinzufΓΌgen

# Adobe
wrangler secret put ADOBE_CLIENT_ID
wrangler secret put ADOBE_CLIENT_SECRET

# Stripe
wrangler secret put STRIPE_SECRET_KEY

# JWT
wrangler secret put JWT_SECRET

Siehe: Secrets Management Guide


πŸ“š Resources

Resource Link
Hono Docs https://hono.dev
Cloudflare Workers https://developers.cloudflare.com/workers/
Drizzle ORM https://orm.drizzle.team
Zod https://zod.dev
Wrangler CLI https://developers.cloudflare.com/workers/wrangler/

πŸŽ‰ READY TO START!

# 1. Create Hono App
cd /Users/gm/Documents/Visual_Code_SHARED/ContractPlattformWhiteLabel
mkdir api && cd api
npm create hono@latest

# 2. Create D1 Database
wrangler d1 create contractplattform-prod

# 3. Create KV Namespace
wrangler kv:namespace create CACHE

# 4. Update wrangler.toml with IDs

# 5. Start Development
npm run dev

# 6. Build Something Awesome! πŸš€

Next: API Deployment Guide β†’