### Application Setup and Routing
Source: https://github.com/srdjan/mixon/blob/main/docs/core-concepts.md
Demonstrates how to set up a Mixon application, register middleware, define routes with parameter types, and start the server.
```APIDOC
## POST /api/users
### Description
This endpoint demonstrates how to set up a Mixon application, register middleware, define routes with parameter types, and start the server.
### Method
POST
### Endpoint
/api/users
### Parameters
#### Path Parameters
- **id** (string) - Required - The ID of the user.
#### Query Parameters
- **limit** (number) - Optional - The maximum number of results to return.
#### Request Body
- **name** (string) - Required - The name of the user.
- **email** (string) - Required - The email of the user.
### Request Example
```json
{
"name": "John Doe",
"email": "john.doe@example.com"
}
```
### Response
#### Success Response (200)
- **message** (string) - A success message.
- **userId** (string) - The ID of the created user.
#### Response Example
```json
{
"message": "User created successfully",
"userId": "123e4567-e89b-12d3-a456-426614174000"
}
```
```
--------------------------------
### Clone and Run Examples
Source: https://github.com/srdjan/mixon/blob/main/README.md
Commands to clone the repository and execute the built-in workflow example.
```bash
# Clone the repository
git clone https://github.com/srdjan/mixon.git
cd Mixon
# Run an example
deno task workflow
```
--------------------------------
### Execute Workflow Examples
Source: https://github.com/srdjan/mixon/blob/main/README.md
Commands to run the workflow example with or without file watching.
```bash
# Run the workflow example
deno task workflow
# Run with file watching (auto-reload on changes)
deno task workflow:watch
```
--------------------------------
### Run the Product Catalog API Example
Source: https://github.com/srdjan/mixon/blob/main/examples/product/README.md
Provides the command to run the Mixon product catalog API example using Deno. Ensure network access is allowed.
```bash
deno run --allow-net examples/product/product-api.ts
```
--------------------------------
### Initialize and Start Mixon Application
Source: https://github.com/srdjan/mixon/blob/main/docs/api-reference.md
Initializes a new Mixon application instance and starts the server, configuring the port, hostname, and a callback for when the server starts listening. Includes graceful shutdown.
```typescript
import { App } from "jsr:@srdjan/mixon";
const app = App();
const { utils } = app;
// Start server
app.listen({
port: 3000,
hostname: "0.0.0.0",
signal: controller.signal,
onListen: ({ hostname, port }) => {
console.log(`Server running at http://${hostname}:${port}/`);
}
});
// Graceful shutdown
app.close();
```
--------------------------------
### Create and Listen on Mixon App
Source: https://github.com/srdjan/mixon/blob/main/JSR.md
Basic setup for a Mixon application. Imports the App class and starts listening on port 3000.
```typescript
import { App } from "jsr:@srdjan/mixon";
const app = App();
const { createResponse } = app.utils;
// Type-safe route parameters
app.get<{ id: string }>("/products/:id", (ctx) => {
const productId = ctx.validated.params.value.id;
const product = { id: productId, name: "Product", price: 29.99 };
// Content negotiation & HATEOAS links
ctx.response = createResponse(ctx, product, {
links: {
self: `/products/${productId}`,
collection: "/products",
related: `/products/${productId}/related`
}
});
});
app.listen(3000);
```
--------------------------------
### Get Products in HTML Format
Source: https://github.com/srdjan/mixon/blob/main/examples/workflow/README.md
Example `curl` command to request product data formatted as HTML for browser rendering.
```bash
curl http://localhost:3000/api/products \
-H "Accept: text/html"
```
--------------------------------
### Get Products in JSON Format
Source: https://github.com/srdjan/mixon/blob/main/examples/workflow/README.md
Example `curl` command to fetch product data in standard JSON format.
```bash
curl http://localhost:3000/api/products \
-H "Accept: application/json"
```
--------------------------------
### Start Server
Source: https://github.com/srdjan/mixon/blob/main/docs/workflow-guide.md
Starts the order workflow server on port 3000 and logs a confirmation message to the console.
```javascript
// Start server
app.listen({
port: 3000,
onListen: ({ hostname, port }) => {
console.log(`Order workflow server running on http://${hostname}:${port}`);
}
});
```
--------------------------------
### Initialize Mixon App and Add Middleware
Source: https://context7.com/srdjan/mixon/llms.txt
Creates a new Mixon application instance, adds global middleware for logging, defines a simple GET route, and starts the server.
```typescript
import { App } from "jsr:@srdjan/mixon";
const app = App();
const { utils } = app;
// Add global middleware for logging
app.use(async (ctx, next) => {
const start = performance.now();
await next();
console.log(`${ctx.request.method} ${ctx.request.url} - ${performance.now() - start}ms`);
});
// Define a simple route
app.get("/hello", (ctx) => {
ctx.response = utils.createResponse(ctx, { message: "Hello World" });
});
// Start the server
app.listen(3000);
console.log("Server running at http://localhost:3000");
```
--------------------------------
### Run Application Tasks
Source: https://github.com/srdjan/mixon/blob/main/README.md
Commands to start the application using the configured Deno tasks.
```bash
deno task start
# or for development with auto-reload
deno task dev
```
--------------------------------
### Get Products in HAL+JSON Format
Source: https://github.com/srdjan/mixon/blob/main/examples/workflow/README.md
Example `curl` command to fetch product data with HATEOAS links, using the HAL+JSON media type.
```bash
curl http://localhost:3000/api/products \
-H "Accept: application/hal+json"
```
--------------------------------
### Install Mixon from JSR
Source: https://github.com/srdjan/mixon/blob/main/JSR.md
Demonstrates how to import the Mixon App class and utilities directly from JSR.
```typescript
// Import directly from JSR (recommended)
import { App } from "jsr:@srdjan/mixon";
// Or import specific utilities
import { App, type, match } from "jsr:@srdjan/mixon";
```
--------------------------------
### Implement Product API
Source: https://github.com/srdjan/mixon/blob/main/docs/core-concepts.md
A complete example of a product API using schema validation, state management, and native Deno server listeners.
```typescript
// product_api.ts
import { App, type, scope, match } from "./deps.ts";
// Define product schema
const productSchema = scope({
name: "string>3",
price: "number>0",
category: "'electronics'|'books'|'clothing'",
inStock: "boolean",
metadata: {
tags: "string[]",
sku: /^[A-Z]{3}-\d{4}$/
}
}).compile();
// Initialize app
const app = App();
const { utils } = app;
// Product data store
const products = new Map();
// Create product endpoint
app.post("/products", async (ctx) => {
return utils.handleResult(
utils.validate(productSchema, ctx.validated.body.value),
ctx,
(product, ctx) => {
const sku = product.metadata.sku;
if (products.has(sku)) {
utils.setStatus(ctx, 409);
return utils.setResponse(ctx, utils.createResponse(ctx, {
error: "Product already exists"
}));
}
products.set(sku, product);
utils.setStatus(ctx, 201);
utils.setHeader(ctx, "Location", `/products/${sku}`);
return utils.setResponse(ctx, utils.createResponse(ctx, product));
},
(error, ctx) => {
utils.setStatus(ctx, 400);
return utils.setResponse(ctx, utils.createResponse(ctx, {
error: "Invalid product data",
details: error
}));
}
);
});
// Start server with native Deno.serve options
app.listen({
port: 3000,
onListen: ({ hostname, port }) => {
console.log(`Product API running on http://${hostname}:${port}/`);
}
});
// Handle graceful shutdown
Deno.addSignalListener("SIGINT", () => {
console.log("Shutting down API server...");
app.close();
});
```
--------------------------------
### Write Integration Tests for API Endpoints
Source: https://github.com/srdjan/mixon/blob/main/docs/best-practices.md
Use Deno's testing utilities to write integration tests for your API endpoints. This example demonstrates testing a GET request for a user, including seeding test data and asserting the response status and content. Ensure the server is started on a random port and properly closed.
```typescript
// api.test.ts
import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
import { app } from "../app.ts";
// Start the app in test mode
const server = app.listen({ port: 0 }); // Random port
const port = server.address?.port;
Deno.test("GET /users/:id - returns user when found", async () => {
// Seed test data
await seedTestUser({ id: "test-user", name: "Test User" });
// Make request
const res = await fetch(`http://localhost:${port}/users/test-user`);
// Assert
assertEquals(res.status, 200);
const data = await res.json();
assertEquals(data.id, "test-user");
assertEquals(data.name, "Test User");
});
Deno.test("GET /users/:id - returns 404 when user not found", async () => {
const res = await fetch(`http://localhost:${port}/users/not-found`);
assertEquals(res.status, 404);
const data = await res.json();
assertEquals(data.error, "User not found");
});
// Clean up
Deno.addSignalListener("SIGINT", () => {
server.close();
});
```
--------------------------------
### Define Routes and Utilities
Source: https://github.com/srdjan/mixon/blob/main/README.md
Example showing how to access utilities and define routes in a Mixon application.
```typescript
// Import Mixon
import { App, type, match } from "jsr:@srdjan/mixon";
// or from Deno.land
// import { App, type, match } from "https://deno.land/x/mixon/mod.ts";
// Create an app instance
const app = App();
// Access utility functions
const { utils } = app;
const { handleError, createResponse, createLinks } = utils;
// Define routes
app.get("/hello", (ctx) => {
ctx.response = createResponse(ctx, { message: "Hello World" });
});
// Start the server
app.listen(3000);
```
--------------------------------
### Integrate HTMX with Mixon
Source: https://context7.com/srdjan/mixon/llms.txt
This example shows a complete setup including a base HTML page with HTMX, fragment endpoints for product lists and details, and stateful controls for cart interactions.
```typescript
/** @jsx h */
import { h, renderSSR } from "nano";
import { App } from "jsr:@srdjan/mixon";
const app = App();
const { utils } = app;
const products = [
{ id: "1", name: "Laptop", price: 999.99, description: "Powerful laptop" },
{ id: "2", name: "Smartphone", price: 699.99, description: "Latest model" },
{ id: "3", name: "Headphones", price: 199.99, description: "Noise-cancelling" }
];
// Home page with HTMX-enabled navigation
app.get("/", (ctx) => {
const html = `
Mixon HTMX Demo
Welcome to the Store
`;
ctx.response = new Response(html, {
headers: { "Content-Type": "text/html" }
});
});
// Product list fragment for HTMX
app.get("/api/fragments/products", (ctx) => {
const html = renderSSR(
{products.map(product => (
{product.name}
${product.price}
))}
);
ctx.response = new Response(html, {
headers: { "Content-Type": "text/html" }
});
});
// Product detail with add to cart
app.get<{ id: string }>("/api/fragments/product/:id", (ctx) => {
const product = products.find(p => p.id === ctx.validated.params.value.id);
if (!product) {
ctx.response = new Response("
`,
{ headers: { "Content-Type": "text/html" } }
);
});
app.listen(3000);
```
--------------------------------
### HAL+JSON Response Example
Source: https://github.com/srdjan/mixon/blob/main/examples/workflow/README.md
Example of a HAL+JSON response for a document, including its state and hypermedia links for related actions and resources.
```json
{
"id": "doc-123",
"title": "Project Proposal",
"state": "Review",
"content": "...",
"_links": {
"self": { "href": "/documents/doc-123" },
"history": { "href": "/documents/doc-123/history" },
"approve": { "href": "/documents/doc-123/approve" },
"reject": { "href": "/documents/doc-123/reject" }
}
}
```
--------------------------------
### Get Product Details with HATEOAS Links
Source: https://github.com/srdjan/mixon/blob/main/examples/workflow/README.md
Fetches details for a specific product, including HATEOAS links for related actions and resources.
```bash
curl http://localhost:3000/api/products/p001 \
-H "Accept: application/hal+json"
```
--------------------------------
### Create Basic API Endpoints
Source: https://github.com/srdjan/mixon/blob/main/README.md
Set up simple GET and POST endpoints with content negotiation and HATEOAS links. Ensure the 'App' function and 'utils' are imported.
```typescript
const app = App();
const { utils } = app;
const { handleError, createResponse, createLinks } = utils;
// Simple endpoint with content negotiation
app.get("/users", (ctx): void => {
const users = [{ id: 1, name: "Alice" }];
// Response format determined by Accept header (JSON, HAL, or HTML)
ctx.response = createResponse(ctx, users);
});
// Validated POST with type safety
app.post("/users", (ctx): void => {
if (!ctx.validated.body.ok) {
handleError(ctx, 400, "Invalid user data", ctx.validated.body.error);
return;
}
const user = ctx.validated.body.value;
const userId = crypto.randomUUID();
ctx.status = 201;
// Create response with HATEOAS links
ctx.response = createResponse(ctx,
{ ...user, id: userId },
{
links: createLinks('users', userId),
// Optional: force specific format regardless of Accept header
// mediaType: MediaType.HAL
}
);
});
app.listen(8000);
```
--------------------------------
### Install Mixon Dependencies
Source: https://github.com/srdjan/mixon/blob/main/docs/core-concepts.md
Import necessary modules from the Mixon Deno deployment.
```typescript
// deps.ts
export { App, type, scope, match } from "https://deno.land/x/Mixon/mod.ts";
```
--------------------------------
### Follow Product Category Link
Source: https://github.com/srdjan/mixon/blob/main/examples/workflow/README.md
Example `curl` command to navigate to a product category resource using a HATEOAS link.
```bash
curl http://localhost:3000/api/products?category=electronics \
-H "Accept: application/hal+json"
```
--------------------------------
### Test API: Get Product Categories with curl
Source: https://github.com/srdjan/mixon/blob/main/examples/product/README.md
Fetches a list of all available product categories using a GET request with curl.
```bash
curl http://localhost:3000/products/categories
```
--------------------------------
### GET /products
Source: https://github.com/srdjan/mixon/blob/main/examples/product/README.md
Retrieves a paginated and filtered list of products.
```APIDOC
## GET /products
### Description
Retrieves a list of products with support for pagination and filtering.
### Method
GET
### Endpoint
/products
### Parameters
#### Query Parameters
- **page** (number) - Optional - The page number for pagination
- **limit** (number) - Optional - The number of items per page
- **category** (string) - Optional - Filter products by category
### Response
#### Success Response (200)
- **products** (array) - List of product objects
- **metadata** (object) - Pagination metadata including total, page, limit, and pages
```
--------------------------------
### Setup zero-md with Mermaid Rendering
Source: https://github.com/srdjan/mixon/blob/main/docs/index.html
Configures zero-md to render Mermaid diagrams by customizing the 'code' renderer. This setup is useful for displaying diagrams within the documentation.
```javascript
app.addEventListener('zero-md-ready', async () => {
const renderer = new marked.Renderer()
renderer.code = function (code, lang) {
return lang === 'mermaid' ? `
${code}
` : `
${code}
`
}
await app.render({ renderer })
mermaid.init()
})
```
--------------------------------
### Test API: Get Product by ID with curl
Source: https://github.com/srdjan/mixon/blob/main/examples/product/README.md
Retrieves details for a specific product using its ID with a GET request via curl. Replace 'p001' with the actual product ID.
```bash
curl http://localhost:3000/products/p001
```
--------------------------------
### Basic API Server with Mixon
Source: https://github.com/srdjan/mixon/blob/main/JSR.md
A simple Mixon application that defines a GET route for '/hello' and responds with 'Hello World'.
```typescript
import { App } from "jsr:@srdjan/mixon";
const app = App();
app.get("/hello", (ctx) => {
ctx.response = new Response("Hello World");
});
app.listen(3000);
```
--------------------------------
### GET /products/categories
Source: https://github.com/srdjan/mixon/blob/main/examples/product/README.md
Lists all available product categories.
```APIDOC
## GET /products/categories
### Description
List all product categories.
### Method
GET
### Endpoint
/products/categories
```
--------------------------------
### Mixon Application Structure Example
Source: https://github.com/srdjan/mixon/blob/main/docs/best-practices.md
A sample directory structure for a Mixon application, organizing code into domain, API, middleware, services, database operations, utilities, and workflows.
```text
src/
├── domain/ # Business domain types and logic
│ ├── user.ts # User domain
│ ├── order.ts # Order domain
│ └── product.ts # Product domain
├── api/ # API endpoints
│ ├── users.ts # User endpoints
│ ├── orders.ts # Order endpoints
│ └── products.ts # Product endpoints
├── middleware/ # Custom middleware
│ ├── auth.ts # Authentication middleware
│ ├── logging.ts # Logging middleware
│ └── metrics.ts # Metrics middleware
├── services/ # External service integrations
│ ├── email.ts # Email service
│ ├── payment.ts # Payment service
│ └── storage.ts # Storage service
├── db/ # Database operations
│ ├── client.ts # Database client
│ ├── users.ts # User repository
│ └── orders.ts # Order repository
├── utils/ # Shared utilities
│ ├── validation.ts # Validation helpers
│ ├── errors.ts # Error handling utilities
│ └── dates.ts # Date manipulation utilities
├── workflows/ # Business workflows
│ ├── order.ts # Order processing workflow
│ └── signup.ts # User signup workflow
└── app.ts # Application bootstrap
```
--------------------------------
### GET /products/{id}
Source: https://github.com/srdjan/mixon/blob/main/examples/product/README.md
Retrieves details for a specific product by its ID.
```APIDOC
## GET /products/{id}
### Description
Get product details by ID.
### Method
GET
### Endpoint
/products/{id}
### Parameters
#### Path Parameters
- **id** (string) - Required - The unique identifier of the product
```
--------------------------------
### Pay for Order Using HATEOAS Link
Source: https://github.com/srdjan/mixon/blob/main/examples/workflow/README.md
Example `curl` command to initiate payment for an order by following a HATEOAS link, providing payment details in JSON.
```bash
curl -X POST http://localhost:3000/api/orders/o123/pay \
-H "Content-Type: application/json" \
-d '{
"paymentMethod": "credit_card",
"cardNumber": "4111111111111111",
"expiryDate": "12/25",
"cvv": "123"
}'
```
--------------------------------
### Define Workflow States, Events, and Transitions
Source: https://github.com/srdjan/mixon/blob/main/docs/api-reference.md
Set up a workflow engine with defined states, events, and transitions. This example defines an order processing workflow.
```typescript
// Define workflow types
type OrderState = "Draft" | "Pending" | "Confirmed" | "Shipped" | "Delivered";
type OrderEvent = "Submit" | "Confirm" | "Ship" | "Deliver" | "Cancel";
// Create workflow engine
const orderWorkflow = app.workflow();
// Define transitions
orderWorkflow.load({
states: ["Draft", "Pending", "Confirmed", "Shipped", "Delivered"],
events: ["Submit", "Confirm", "Ship", "Deliver", "Cancel"],
transitions: [
{
from: "Draft",
to: "Pending",
on: "Submit",
task: {
assign: "sales@example.com",
message: "New order received: {orderNumber}"
}
},
// Additional transitions...
],
initial: "Draft"
});
```
--------------------------------
### Workflow Engine Setup
Source: https://github.com/srdjan/mixon/blob/main/docs/core-concepts.md
Defines and loads a state machine workflow using Mixon's workflow engine, including states, events, and transitions.
```APIDOC
## POST /orders/:id/transitions
### Description
Handles transitions within an order workflow. This endpoint is part of the workflow engine setup.
### Method
POST
### Endpoint
/orders/:id/transitions
### Parameters
#### Path Parameters
- **id** (string) - Required - The ID of the order.
#### Request Body
- **event** (string) - Required - The event to trigger a transition (e.g., "Submit", "Confirm").
- **taskData** (object) - Optional - Data associated with the task.
### Request Example
```json
{
"event": "Submit",
"taskData": {
"orderNumber": "ORD-12345"
}
}
```
### Response
#### Success Response (200)
- **message** (string) - Confirmation message of the transition.
- **newState** (string) - The new state of the workflow.
#### Response Example
```json
{
"message": "Transition successful.",
"newState": "Pending"
}
```
```
--------------------------------
### Test API: Search Products with curl
Source: https://github.com/srdjan/mixon/blob/main/examples/product/README.md
Searches for products based on a query string using a GET request with curl. The 'q' parameter specifies the search term.
```bash
curl http://localhost:3000/products/search?q=mouse
```
--------------------------------
### Setup Left Side Menu and Article Content Selection
Source: https://github.com/srdjan/mixon/blob/main/docs/index.html
Implements functionality for a left-side menu that highlights selected items and updates the main article content. It uses data attributes to link menu items to content sources.
```javascript
const dts = document.querySelectorAll('dt');
dts.forEach(dt => dt.addEventListener('click', highlight, false));
function highlight(e) {
dts.forEach(item => item.classList.remove('dt-border'));
let id = e.target.dataset.id;
let dt = document.querySelector(`dt[data-id="${id}"]`);
dt.classList.add('dt-border');
// change article content
let zeromd = document.getElementById('app')
zeromd.setAttribute('src', `${e.target.dataset.src}`)
let article = document.getElementById('article')
article.replaceWith(article)
}
```
--------------------------------
### Memory-optimized Dockerfile setup
Source: https://github.com/srdjan/mixon/blob/main/docs/mem-optimization.md
Configures a Docker container for a Deno application with specific V8 memory limits. This Dockerfile sets environment variables to control `--max-old-space-size` and `--max-heap-size` for optimized memory usage.
```dockerfile
FROM denoland/deno:1.43
WORKDIR /app
COPY . .
# Set memory limits
ENV V8_FLAGS="--max-old-space-size=512,--max-heap-size=1024"
# Run with optimizations
CMD ["run", "--allow-net", "--allow-env", "server.ts"]
```
--------------------------------
### Compose Middleware Strategically
Source: https://github.com/srdjan/mixon/blob/main/docs/best-practices.md
Apply middleware globally, per domain, or per route. This example shows how to combine global, domain-specific, and route-specific middleware for flexible request handling.
```typescript
// Global middleware (applied to all routes)
app.use(requestLogger);
app.use(errorHandler);
// Domain-specific middleware
const userMiddleware = [
authenticate,
auditLog("users")
];
// Route-specific middleware composition
app.get("/users", ...userMiddleware, listUsers);
app.post("/users", ...userMiddleware, validateUserData, createUser);
// Conditional middleware
const conditionalAuth = (ctx, next) => {
const path = new URL(ctx.request.url).pathname;
if (path.startsWith("/admin")) {
return authenticate(ctx, next);
}
return next();
};
```
--------------------------------
### Apply Global and Route-Specific Middleware
Source: https://github.com/srdjan/mixon/blob/main/docs/api-reference.md
Shows how to apply middleware globally to all routes or to specific routes. Includes an example of logging request duration and an authentication middleware.
```typescript
// Global middleware
app.use(async (ctx, next) => {
const start = performance.now();
await next();
console.log(`${ctx.request.method} ${ctx.request.url} - ${performance.now() - start}ms`);
});
// Authentication middleware
const authenticate = async (ctx: Context, next: Next) => {
const token = ctx.request.headers.get("Authorization")?.split(" ")[1];
if (!token) {
utils.setStatus(ctx, 401);
return utils.setResponse(ctx, utils.createResponse(ctx, { error: "Unauthorized" }));
}
ctx.state.user = await validateToken(token);
await next();
};
// Apply middleware to specific routes
app.get("/protected", authenticate, protectedResourceHandler);
```
--------------------------------
### Register Basic and Parameterized Routes
Source: https://github.com/srdjan/mixon/blob/main/docs/api-reference.md
Demonstrates how to register basic GET and POST routes, as well as routes with path parameters. Supports type-safe access to validated parameters and request bodies.
```typescript
// Basic route handlers
app.get("/", (ctx) => {
return utils.setResponse(ctx, utils.createResponse(ctx, { message: "Hello World" }));
});
// Path parameters (type-safe)
app.get<{ id: string }>("/users/:id", (ctx) => {
// Type-safe access to ctx.validated.params.value.id
});
// Generic parametric routes
app.post<{ id: string }, UserPayload>("/users/:id", (ctx) => {
// Type-safe access to validated body and params
});
// HTTP method variants
app.post("/resources", createResourceHandler);
app.put("/resources/:id", updateResourceHandler);
app.delete("/resources/:id", deleteResourceHandler);
```
--------------------------------
### Add Product to Cart Using HATEOAS Link
Source: https://github.com/srdjan/mixon/blob/main/examples/workflow/README.md
Example `curl` command to add a product to the shopping cart by following a HATEOAS link, sending JSON data.
```bash
curl -X POST http://localhost:3000/api/cart/add \
-H "Content-Type: application/json" \
-d '{
"productId": "p001",
"quantity": 1
}'
```
--------------------------------
### Get Order with Available Actions
Source: https://github.com/srdjan/mixon/blob/main/examples/workflow/README.md
Fetches order details, including HATEOAS links representing available actions based on the order's current state.
```bash
curl http://localhost:3000/api/orders/o123 \
-H "Accept: application/hal+json"
```
--------------------------------
### Implement Graceful Shutdown with Signal Handling
Source: https://github.com/srdjan/mixon/blob/main/docs/best-practices.md
Ensure proper cleanup during application shutdown by listening for termination signals like SIGINT and SIGTERM. This example shows how to abort the server's signal, close database connections, and perform other necessary cleanup tasks before exiting the process.
```typescript
// app.ts
import { App } from "jsr:@srdjan/mixon";
const app = App();
// Setup routes
setupRoutes(app);
// Start server
const controller = new AbortController();
const server = app.listen({
port: 3000,
signal: controller.signal
});
// Graceful shutdown
const shutdown = async () => {
console.log("Shutting down gracefully...");
// Close server
controller.abort();
// Close database connections
await closeDatabase();
// Other cleanup
console.log("Cleanup complete");
Deno.exit(0);
};
// Listen for termination signals
Deno.addSignalListener("SIGINT", shutdown);
Deno.addSignalListener("SIGTERM", shutdown);
```
--------------------------------
### Format Responses Consistently with HATEOAS Links
Source: https://github.com/srdjan/mixon/blob/main/docs/best-practices.md
Ensure consistent response formatting by using utility functions to create standardized responses, including HATEOAS links and metadata. This example shows how to generate self and collection links, extend them with custom links, and include pagination metadata.
```typescript
// Create standardized HATEOAS links
const links = createLinks('products', productId);
// Result: { self: '/products/123', collection: '/products' }
// Extend with custom links
const customLinks = {
...createLinks('products', productId),
reviews: `/products/${productId}/reviews`,
related: `/products/${productId}/related`
};
// Create response with links
ctx.response = createResponse(ctx, product, { links: customLinks });
// Create response with metadata
ctx.response = createResponse(ctx, results, {
meta: {
total: 100,
page: 1,
limit: 10
}
});
```
--------------------------------
### Initialize a Basic Application
Source: https://github.com/srdjan/mixon/blob/main/README.md
Create a simple server instance and define a root route.
```typescript
import { App } from "jsr:@srdjan/mixon";
const app = App();
const { utils } = app;
app.get("/", (ctx) => {
ctx.response = utils.createResponse(ctx, { message: "Hello from Mixon!" });
});
console.log("Server running at http://localhost:3000");
app.listen(3000);
```
--------------------------------
### Initialize Mock Database and Sample Order
Source: https://github.com/srdjan/mixon/blob/main/docs/workflow-guide.md
Sets up a simple in-memory database using a Map to store orders and initializes it with a sample order in the 'Draft' state. This is used for demonstration purposes.
```typescript
// Mock database
const db = {
orders: new Map()
};
// Initialize with sample order
db.orders.set("order-1", {
id: "order-1",
customer: "John Doe",
items: [
{ product: "Widget A", quantity: 2, price: 10.99 },
{ product: "Widget B", quantity: 1, price: 24.99 }
],
totalAmount: 46.97,
state: "Draft",
stateHistory: [],
createdAt: new Date(),
updatedAt: new Date()
});
```
--------------------------------
### Create and Use a Database Connection Pool
Source: https://github.com/srdjan/mixon/blob/main/docs/best-practices.md
Demonstrates how to create a database connection pool with specified minimum and maximum connections, and how to use middleware to acquire and release connections for requests.
```typescript
// Create a database connection pool
const dbPool = createPool({
min: 5,
max: 20,
create: () => createConnection(DB_URL),
destroy: (conn) => conn.close(),
});
// Database middleware to provide connections
app.use(async (ctx, next) => {
const connection = await dbPool.acquire();
try {
ctx.state.db = connection;
await next();
} finally {
await dbPool.release(connection);
}
});
```
--------------------------------
### App Initialization
Source: https://context7.com/srdjan/mixon/llms.txt
How to initialize a Mixon application, add middleware, and define basic routes.
```APIDOC
## App Initialization
### Description
Initializes a new Mixon application instance to handle routing, middleware, and utility functions.
### Request Example
```typescript
import { App } from "jsr:@srdjan/mixon";
const app = App();
app.listen(3000);
```
```
--------------------------------
### Configure Optimized Server Settings
Source: https://github.com/srdjan/mixon/blob/main/docs/perf-optimization.md
Set up the Deno HTTP server with connection limits and TLS configuration.
```typescript
app.listen({
port: 3000,
hostname: "0.0.0.0",
// Signal for controlled shutdown
signal: controller.signal,
// Callback when server is listening
onListen({ hostname, port }) {
console.log(`Server running on http://${hostname}:${port}/`);
},
// Maximum number of concurrent connections
maxConnections: 10000,
// TLS configuration for HTTPS
cert: Deno.readTextFileSync("./cert.pem"),
key: Deno.readTextFileSync("./key.pem"),
});
```
--------------------------------
### GET /products/search
Source: https://github.com/srdjan/mixon/blob/main/examples/product/README.md
Searches for products based on a text query.
```APIDOC
## GET /products/search
### Description
Search products by text query.
### Method
GET
### Endpoint
/products/search
### Parameters
#### Query Parameters
- **q** (string) - Required - The search query string
```
--------------------------------
### Test API: Create Product with curl
Source: https://github.com/srdjan/mixon/blob/main/examples/product/README.md
Demonstrates how to create a new product using a POST request with curl. Ensure the 'Content-Type' header is set to 'application/json' and provide product details in the request body.
```bash
curl -X POST http://localhost:3000/products \
-H "Content-Type: application/json" \
-d '{
"name": "Bluetooth Headphones",
"description": "Noise cancelling wireless headphones",
"price": 149.99,
"category": "electronics",
"inStock": true,
"quantity": 30
}'
```
--------------------------------
### Initialize and Configure Mixon Application
Source: https://github.com/srdjan/mixon/blob/main/docs/core-concepts.md
Set up a new Mixon application instance, register middleware, and define route handlers.
```typescript
import { App } from "./deps.ts";
const app = App();
const { utils } = app;
// Middleware registration
app.use(async (ctx, next) => {
const start = performance.now();
await next();
console.log(`${ctx.request.method} ${ctx.request.url} - ${performance.now() - start}ms`);
});
// Route handlers
app.get<{ id: string }>("/resources/:id", async (ctx) => {
return utils.handleResult(ctx.validated.params, ctx,
(params, ctx) => {
// Success handler with ctx mutation
return utils.setResponse(ctx, utils.createResponse(ctx, { id: params.id }));
},
(error, ctx) => {
// Error handler with ctx mutation
utils.setStatus(ctx, 400);
return utils.setResponse(ctx, utils.createResponse(ctx, { error }));
}
);
});
// Start the server
app.listen({ port: 3000 });
```
--------------------------------
### Configure Permissions
Source: https://github.com/srdjan/mixon/blob/main/README.md
Minimal configuration for required network and file system permissions.
```json
{
"permissions": {
"net": true,
"read": true,
"write": true
}
}
```
--------------------------------
### Create Responses with Content Negotiation
Source: https://context7.com/srdjan/mixon/llms.txt
Shows how to use createResponse to handle different media types, HATEOAS links, and metadata.
```typescript
import { App } from "jsr:@srdjan/mixon";
const app = App();
const { utils } = app;
const { createResponse, createLinks, MediaType } = utils;
const product = { id: "123", name: "Widget", price: 29.99 };
app.get("/products/:id", (ctx) => {
// Basic response - format determined by Accept header
ctx.response = createResponse(ctx, product);
});
app.get("/products/:id/full", (ctx) => {
// Response with HATEOAS links
ctx.response = createResponse(ctx, product, {
links: {
self: `/products/${product.id}`,
collection: "/products",
reviews: `/products/${product.id}/reviews`
}
});
});
app.get("/products/:id/meta", (ctx) => {
// Response with links and metadata
ctx.response = createResponse(ctx, product, {
links: createLinks("products", product.id),
meta: {
version: "1.0",
timestamp: new Date().toISOString()
}
});
});
app.get("/products/:id/json", (ctx) => {
// Force JSON format regardless of Accept header
ctx.response = createResponse(ctx, product, {
mediaType: MediaType.JSON,
links: createLinks("products", product.id)
});
});
app.get("/products/:id/hal", (ctx) => {
// Force HAL format for hypermedia clients
ctx.response = createResponse(ctx, product, {
mediaType: MediaType.HAL,
links: {
self: { href: `/products/${product.id}` },
collection: { href: "/products" }
}
});
});
app.listen(3000);
// curl http://localhost:3000/products/123 -H "Accept: application/json"
// {"data":{"id":"123","name":"Widget","price":29.99}}
// curl http://localhost:3000/products/123/full -H "Accept: application/hal+json"
// {"id":"123","name":"Widget","price":29.99,"_links":{"self":"/products/123","collection":"/products","reviews":"/products/123/reviews"}}
```
--------------------------------
### Handle Conflict Errors
Source: https://github.com/srdjan/mixon/blob/main/docs/utility-functions.md
Example of calling `handleError` for a 409 conflict error, providing an object with details about the existing resource.
```typescript
// Conflict error
utils.handleError(ctx, 409, "Resource already exists", {
id: existingId
});
```
--------------------------------
### Handle Validation Errors
Source: https://github.com/srdjan/mixon/blob/main/docs/utility-functions.md
Example of calling `handleError` for a 400 validation error, providing an array of validation messages as details.
```typescript
// Validation error
utils.handleError(ctx, 400, "Invalid request data", [
"Name is required",
"Email must be valid"
]);
```
--------------------------------
### POST /products
Source: https://github.com/srdjan/mixon/blob/main/examples/product/README.md
Creates a new product in the catalog.
```APIDOC
## POST /products
### Description
Create a new product.
### Method
POST
### Endpoint
/products
### Request Body
- **name** (string) - Required
- **description** (string) - Required
- **price** (number) - Required
- **category** (string) - Required
- **inStock** (boolean) - Required
- **quantity** (number) - Required
```
--------------------------------
### Handle Basic Errors
Source: https://github.com/srdjan/mixon/blob/main/docs/utility-functions.md
Example of calling `handleError` for a basic 404 error. The response format is determined by the `Accept` header.
```typescript
// Basic error (format determined by Accept header)
utils.handleError(ctx, 404, "Resource not found");
```
--------------------------------
### Search with Auto-Complete using HTMX
Source: https://github.com/srdjan/mixon/blob/main/docs/htmx-integration.md
An input field that triggers a GET request to '/api/search' on keyup with a delay, updating the '#results' div.
```html
```
--------------------------------
### Run Development Tasks
Source: https://github.com/srdjan/mixon/blob/main/README.md
Execute common development commands using Deno tasks for testing, formatting, and linting.
```bash
# Development setup
denp task test
denp task fmt
denp task lint
```
--------------------------------
### Perform Simple Pattern Matching with Mixon
Source: https://github.com/srdjan/mixon/blob/main/docs/api-reference.md
Use the `match` function for type-safe conditional logic. This example demonstrates matching against status codes.
```typescript
import { match } from "jsr:@srdjan/mixon";
// Simple pattern matching
return match(statusCode)
.with(200, () => "OK")
.with(404, () => "Not Found")
.with(500, () => "Server Error")
.otherwise(() => "Unknown Status");
```
--------------------------------
### Implement Performance Tracking Middleware
Source: https://github.com/srdjan/mixon/blob/main/examples/product/README.md
Adds middleware for tracking request processing time. It measures the duration from the start of the request to its completion and logs it to the console.
```typescript
// Performance tracking middleware
const start = performance.now();
try {
await next();
// ... handle the request
} finally {
const duration = performance.now() - start;
console.log(`Request processed in ${duration.toFixed(2)}ms`);
}
```
--------------------------------
### Get Available Actions for State
Source: https://context7.com/srdjan/mixon/llms.txt
Determines the possible events that can occur from a given workflow state. Uses a `match` statement for exhaustive checking of states.
```typescript
// Get available actions for current state
const getAvailableActions = (state: OrderState): OrderEvent[] =>
match(state)
.with("Draft", () => ["Submit", "Cancel"] as OrderEvent[])
.with("Submitted", () => ["Process", "Cancel"] as OrderEvent[])
.with("Processing", () => ["Ship", "Cancel"] as OrderEvent[])
.with("Shipped", () => ["Deliver"] as OrderEvent[])
.with("Delivered", () => [] as OrderEvent[])
.with("Cancelled", () => [] as OrderEvent[])
.exhaustive();
```
--------------------------------
### Get Order Endpoint
Source: https://github.com/srdjan/mixon/blob/main/docs/workflow-guide.md
Retrieves a specific order by its ID. Returns the order details and available actions if found, otherwise returns a 404 error.
```javascript
// Get order endpoint
app.get<{ id: string }>("/orders/:id", async (ctx) => {
return utils.handleResult(ctx.validated.params, ctx,
async (params, ctx) => {
const order = db.orders.get(params.id);
if (!order) {
utils.setStatus(ctx, 404);
return utils.setResponse(ctx, utils.createResponse(ctx, {
error: "Order not found"
}));
}
return utils.setResponse(ctx, utils.createResponse(ctx, {
order,
allowedEvents: getAvailableActions(order.state)
}));
},
(errors, ctx) => {
utils.setStatus(ctx, 400);
return utils.setResponse(ctx, utils.createResponse(ctx, {
error: "Invalid order ID",
details: errors
}));
}
);
});
```
--------------------------------
### Configure deno.json
Source: https://github.com/srdjan/mixon/blob/main/README.md
Define project tasks and required permissions in the deno.json configuration file.
```json
{
"tasks": {
"start": "deno run --allow-net --allow-read main.ts",
"dev": "deno run --watch --allow-net --allow-read main.ts"
},
"permissions": {
"net": true,
"read": true,
"write": true
}
}
```
--------------------------------
### Pattern Matching with Data Extraction in Mixon
Source: https://github.com/srdjan/mixon/blob/main/docs/api-reference.md
Extract data from matched patterns to use in conditional logic. This example matches user roles and verification status.
```typescript
return match(user)
.with({ role: "admin" }, (admin) => adminDashboard(admin))
.with({ role: "user", verified: true }, (user) => userDashboard(user))
.with({ role: "user", verified: false }, () => verificationScreen())
.otherwise(() => loginScreen());
```
--------------------------------
### Define and Use a Workflow Engine
Source: https://github.com/srdjan/mixon/blob/main/docs/best-practices.md
Illustrates defining a workflow with states, events, and transitions, and using pattern matching to determine actions based on the current state.
```typescript
// Define workflow with clear states and transitions
const orderWorkflow = app.workflow();
orderWorkflow.load({
states: ["Draft", "Submitted", "Processing", "Shipped", "Delivered", "Cancelled"],
events: ["Submit", "Process", "Ship", "Deliver", "Cancel"],
transitions: [
// From Draft, can only Submit or Cancel
{ from: "Draft", to: "Submitted", on: "Submit" },
{ from: "Draft", to: "Cancelled", on: "Cancel" },
// From Submitted, can Process or Cancel
{ from: "Submitted", to: "Processing", on: "Process" },
{ from: "Submitted", to: "Cancelled", on: "Cancel" },
// From Processing, can Ship or Cancel
{ from: "Processing", to: "Shipped", on: "Ship" },
{ from: "Processing", to: "Cancelled", on: "Cancel" },
// From Shipped, can only Deliver
{ from: "Shipped", to: "Delivered", on: "Deliver" },
],
initial: "Draft"
});
// Use pattern matching for state-dependent behavior
const getOrderActions = (order: Order): string[] =>
match(order.state)
.with("Draft", () => ["Submit", "Cancel"])
.with("Submitted", () => ["Process", "Cancel"])
.with("Processing", () => ["Ship", "Cancel"])
.with("Shipped", () => ["Deliver"])
.with("Delivered", () => [])
.with("Cancelled", () => [])
.exhaustive();
```
--------------------------------
### Get Task for Transition
Source: https://github.com/srdjan/mixon/blob/main/examples/workflow/README.md
Retrieve the task details for a specific transition based on the current event and document state. Used for assigning tasks and sending messages.
```typescript
const task = docWorkflow.getTaskForTransition(event, doc.state);
sendEmail(task.assign, task.message);
```