DeployCode Deployment
Deployment Examples
Complete examples of deploying MDX Functions & Components
Documentation Status: This documentation describes the planned API design for the .do platform. Code examples represent the intended interface and may not reflect the current implementation state. See roadmap for implementation status.
Real-world examples of deploying MDX Functions & Components to various targets.
Example 1: Todo App (All Targets)
A single MDX file deployed to multiple targets:
---
title: Todo Management
description: Complete todo application
---
// ============================================================================
// FUNCTIONS - Business logic
// ============================================================================
export async function getTodos(userId: string) {
return db.Todos.list({ where: { userId }, orderBy: { createdAt: 'desc' } })
}
export async function createTodo(userId: string, title: string) {
return db.Todos.create({
userId,
title,
completed: false,
createdAt: new Date(),
})
}
export async function updateTodo(id: string, updates: Partial<Todo>) {
return db.Todos.update(id, updates)
}
export async function deleteTodo(id: string) {
return db.Todos.delete(id)
}
// ============================================================================
// COMPONENTS - User interface
// ============================================================================
export function TodoList({ todos, onToggle, onDelete }) {
return (
<ul className="todo-list">
{todos.map((todo) => (
<li key={todo.id} className={todo.completed ? 'completed' : ''}>
<input type="checkbox" checked={todo.completed} onChange={() => onToggle(todo.id, !todo.completed)} />
<span>{todo.title}</span>
<button onClick={() => onDelete(todo.id)}>Delete</button>
</li>
))}
</ul>
)
}
export function TodoApp() {
const user = $.auth.useUser()
const [todos, setTodos] = useState([])
const [newTodo, setNewTodo] = useState('')
useEffect(() => {
if (user) {
getTodos(user.id).then(setTodos)
}
}, [user])
async function handleAdd(e) {
e.preventDefault()
const todo = await createTodo(user.id, newTodo)
setTodos([todo, ...todos])
setNewTodo('')
}
async function handleToggle(id, completed) {
updateTodo(id, { completed })
setTodos(todos.map((t) => (t.id === id ? { ...t, completed } : t)))
}
async function handleDelete(id) {
deleteTodo(id)
setTodos(todos.filter((t) => t.id !== id))
}
return (
<div className="todo-app">
<h1>My Todos</h1>
<form onSubmit={handleAdd}>
<input value={newTodo} onChange={(e) => setNewTodo(e.target.value)} placeholder="Add a todo..." />
<button type="submit">Add</button>
</form>
<TodoList todos={todos} onToggle={handleToggle} onDelete={handleDelete} />
</div>
)
}Deploy as API
// REST API
export default {
apis: {
'/api/todos': {
GET: async (req) => getTodos(req.user.id),
POST: async (req) => createTodo(req.user.id, req.body.title),
},
'/api/todos/:id': {
PUT: async (req) => updateTodo(req.params.id, req.body),
DELETE: async (req) => deleteTodo(req.params.id),
},
},
}Deploy as App
// Full-stack application
export default {
apps: [
{
name: 'todo-app',
component: TodoApp,
domain: 'todos.example.do',
},
],
}Deploy as Agent
// Autonomous todo manager
export const todoAgent = $.agent({
name: 'Todo Assistant',
capabilities: { getTodos, createTodo, updateTodo, deleteTodo },
triggers: [
$.on('email.received', async (email) => {
if (email.subject.includes('TODO:')) {
const title = email.subject.replace('TODO:', '').trim()
await createTodo(email.from.userId, title)
}
}),
],
})Example 2: Newsletter Service
Complete newsletter service with subscription management:
---
title: Newsletter Service
description: Email newsletter service
---
export async function subscribe(email: string, lists: string[]) {
// Validate email
if (!isValidEmail(email)) {
throw new ValidationError('Invalid email address')
}
// Create subscriber
const subscriber = await db.Subscribers.create({
email,
lists,
status: 'active',
subscribedAt: new Date(),
})
// Send welcome email
send.Email({
to: email,
template: 'welcome',
data: { lists },
})
return subscriber
}
export async function sendNewsletter(listId: string, content: { subject: string; body: string }) {
const subscribers = await db.Subscribers.list({
where: { lists: { contains: listId }, status: 'active' },
})
const results = await Promise.all(
subscribers.map((sub) =>
send.Email({
to: sub.email,
subject: content.subject,
body: content.body,
})
)
)
return {
sent: results.filter((r) => r.success).length,
failed: results.filter((r) => !r.success).length,
}
}
export function SubscribeForm() {
const [email, setEmail] = useState('')
const [status, setStatus] = useState('idle')
async function handleSubmit(e) {
e.preventDefault()
setStatus('loading')
try {
await subscribe(email, ['general'])
setStatus('success')
setEmail('')
} catch (error) {
setStatus('error')
}
}
return (
<form onSubmit={handleSubmit} className="subscribe-form">
<h3>Subscribe to our newsletter</h3>
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="[email protected]" required />
<button type="submit" disabled={status === 'loading'}>
{status === 'loading' ? 'Subscribing...' : 'Subscribe'}
</button>
{status === 'success' && <p className="success">Thanks for subscribing!</p>}
{status === 'error' && <p className="error">Error. Please try again.</p>}
</form>
) }Deploy as Service
export default $.service({
name: 'newsletter-service',
version: '1.0.0',
capabilities: { subscribe, sendNewsletter },
pricing: {
model: 'subscription',
plans: [
{ name: 'Starter', price: 29, features: ['1000 subscribers', '4 newsletters/month'] },
{ name: 'Pro', price: 99, features: ['10000 subscribers', 'unlimited newsletters'] },
],
},
})Deploy as Workflow
export const newsletterWorkflow = $.workflow('send-newsletter', async (params) => {
// Step 1: Create content
const content = await $.step('create', () => generateNewsletterContent(params.topic))
// Step 2: Review
const reviewed = await $.step('review', () => $.human.request({ type: 'newsletter_review', content }))
// Step 3: Send
const result = await $.step('send', () => sendNewsletter(params.listId, reviewed))
return result
})Example 3: E-Commerce Product Catalog
Product management system:
---
title: Product Catalog
description: E-commerce product management
---
export async function getProducts(filters: {
category?: string
minPrice?: number
maxPrice?: number
inStock?: boolean
}) {
let query = db.Products.query()
if (filters.category) {
query = query.where('category', '=', filters.category)
}
if (filters.minPrice) {
query = query.where('price', '>=', filters.minPrice)
}
if (filters.maxPrice) {
query = query.where('price', '<=', filters.maxPrice)
}
if (filters.inStock) {
query = query.where('stock', '>', 0)
}
return query.execute()
}
export async function getProduct(id: string) {
return db.Products.get(id)
}
export function ProductCard({ product }) {
return (
<div className="product-card">
<img src={product.image} alt={product.name} />
<h3>{product.name}</h3>
<p className="price">${product.price}</p>
<p className="description">{product.description}</p>
{product.stock > 0 ? <button onClick={() => $.cart.add(product)}>Add to Cart</button> : <span className="out-of-stock">Out of Stock</span>}
</div>
)
}
export function ProductCatalog({ category }) {
const { data: products, loading } = $.data.use(() => getProducts({ category, inStock: true }))
if (loading) return <Loading />
return (
<div className="product-catalog">
<h1>{category ? `${category} Products` : 'All Products'}</h1>
<div className="product-grid">
{products.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
</div>
)
}Deploy as Site
export default {
sites: [{
name: 'product-catalog',
source: './catalog.mdx',
deployment: {
type: 'ssr',
domain: 'shop.example.do',
routes: {
'/': () => <ProductCatalog />,
'/category/:category': ({ params }) => <ProductCatalog category={params.category} />,
'/product/:id': ({ params }) => <ProductPage id={params.id} />
}
}
}]
}Example 4: Analytics Dashboard
Real-time analytics dashboard:
---
title: Analytics Dashboard
description: Real-time business analytics
---
export async function getMetrics(period: 'day' | 'week' | 'month' | 'year') {
const metrics = await $.analytics.query({
metrics: ['pageviews', 'users', 'sessions', 'revenue'],
period,
groupBy: 'day'
})
return metrics
}
export async function getTopPages(limit = 10) {
return await $.analytics.query({
metrics: ['pageviews'],
dimensions: ['page'],
orderBy: { pageviews: 'desc' },
limit,
})
}
export function MetricsCard({ title, value, change }) {
const isPositive = change >= 0
return (
<div className="metrics-card">
<h3>{title}</h3>
<div className="value">{value}</div>
<div className={`change ${isPositive ? 'positive' : 'negative'}`}>
{isPositive ? '↑' : '↓'} {Math.abs(change)}%
</div>
</div>
)
}
export function AnalyticsDashboard() {
const [period, setPeriod] = useState('week')
const metrics = $.data.use(() => getMetrics(period), [period])
const topPages = $.data.use(() => getTopPages())
return (
<div className="analytics-dashboard">
<header>
<h1>Analytics</h1>
<select value={period} onChange={(e) => setPeriod(e.target.value)}>
<option value="day">Last 24 Hours</option>
<option value="week">Last 7 Days</option>
<option value="month">Last 30 Days</option>
<option value="year">Last Year</option>
</select>
</header>
<div className="metrics-grid">
<MetricsCard title="Pageviews" value={metrics.data?.pageviews} change={5.2} />
<MetricsCard title="Users" value={metrics.data?.users} change={-2.1} />
<MetricsCard title="Sessions" value={metrics.data?.sessions} change={3.5} />
<MetricsCard title="Revenue" value={`$${metrics.data?.revenue}`} change={12.3} />
</div>
<div className="charts">
<LineChart data={metrics.data?.timeseries} title="Traffic Over Time" />
<BarChart data={topPages.data} title="Top Pages" />
</div>
</div>
)
}Deploy as App
export default {
apps: [
{
name: 'analytics-dashboard',
component: AnalyticsDashboard,
domain: 'analytics.example.do',
auth: {
required: true,
roles: ['admin', 'analyst'],
},
},
],
}Multi-Target Deployment Example
Deploy the same code to all targets:
// do.config.ts
import * as todos from './todos.mdx'
export default {
// As API
apis: [
{
name: 'todos-api',
source: './todos.mdx',
deployment: {
domain: 'api.todos.do',
endpoints: {
'/todos': { GET: todos.getTodos, POST: todos.createTodo },
'/todos/:id': { PUT: todos.updateTodo, DELETE: todos.deleteTodo },
},
},
},
],
// As App
apps: [
{
name: 'todos-app',
source: './todos.mdx',
component: todos.TodoApp,
domain: 'app.todos.do',
},
],
// As Agent
agents: [
{
name: 'todos-agent',
source: './todos.mdx',
capabilities: {
getTodos: todos.getTodos,
createTodo: todos.createTodo,
},
triggers: ['email.received'],
},
],
// As Workflow
workflows: [
{
name: 'todo-processor',
source: './todos.mdx',
steps: ['getTodos', 'processTodos', 'notifyUser'],
},
],
}Related Documentation
- Code Deployment - Overview and concepts
- Configuration - Deployment configuration
- Build Process - Build and deployment
-
- Best Practices - Development best practices