Skip to content

Commit

Permalink
Merge pull request #56 from brandon-schabel/usage-examples
Browse files Browse the repository at this point in the history
Server and SQLite Usage Examples
  • Loading branch information
brandon-schabel authored Nov 12, 2023
2 parents 91710e8 + e7edcb2 commit 22b837d
Show file tree
Hide file tree
Showing 2 changed files with 190 additions and 0 deletions.
90 changes: 90 additions & 0 deletions docs/usage/SERVER-USAGE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
### Server Module Usage Guide with TypeScript and HTMLody Integration

---

## Introduction

The Bun Nook Kit Server Module is designed for creating robust servers in Bun-based applications. It emphasizes type safety and modularity, integrating request handling, dynamic routing, middleware management, CORS configurations, and server utilities.

---

## Key Features

1. **Type-Safe Middleware**: Ensures structure and return type consistency for each middleware function.
2. **Type-Safe Routes**: Defines routes with HTTP methods and their corresponding handlers, maintaining type consistency.
3. **Server Factory with Type Safety**: Guarantees correct types for middleware and routes, ensuring consistent and predictable server behavior.

---

## Usage Examples

### 1. Defining Middleware with Types

```typescript
import { Middleware, MiddlewareConfigMap } from '@bnk/core/modules/server';

const timeMiddleware: Middleware<
{ test1: string },
{ timestamp: Date }
> = (req, options) => {
return { timestamp: new Date() };
};

const corsHeaders: Middleware<
{},
{ requestHeaders: Headers }
> = (request) => {
return { requestHeaders: request.headers };
};

const middleware = { time: timeMiddleware, cors: corsHeaders } satisfies MiddlewareConfigMap;
```

### 2. Creating Type-Safe Routes

```typescript
import { Routes } from '@bnk/core/modules/server';

const routes: Routes<{ middleware: typeof middleware }> = {
"/": {
GET: (req, mid) => new Response(`Hello World! ${mid?.time?.timestamp}`)
},
// other routes
} satisfies Routes<{ middleware: typeof middleware }>;
```

### 3. Configuring and Starting the Server

```typescript
import { serverFactory, middlewareFactory } from '@bnk/core/modules/server';

const middlewareControl = middlewareFactory(middleware);

const { start } = serverFactory({
middlewareControl,
routes,
});

start(3000); // Start the server on port 3000
```

### 4. Integration with HTMLody

Integrating the server with HTMLody can be done by using HTMLody to generate HTML content for server responses. For example, you can create a route that returns an HTMLody-generated page:

```typescript
import { jsonToHtml } from '@bnk/core/modules/htmlody';
import { htmlRes } from '@bnk/core/modules/server'

const htmlRoute: RouteHandler = (req, mid) => {
const page = /* Define your HTMLody page here */;
const htmlContent = jsonToHtml(page);

return htmlRes(htmlContent)
};

// Add htmlRoute to your routes
routes["/html"] = { GET: htmlRoute };
```

## TODO: Add HTMLody builder xample
100 changes: 100 additions & 0 deletions docs/usage/SQLITE-USAGE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
### SQLite Module Usage Guide with TypeScript

---

## Introduction

The SQLite Module in the Bun Nook Kit provides a seamless integration of SQLite databases with TypeScript. Its standout feature is generating TypeScript types from SQLite schema definitions, ensuring type safety and consistency between the database schema and TypeScript code.

---

## Key Features

1. **TypeScript-Inferred SQLite Schemas**
- Automatically translates SQLite table schemas into TypeScript types.
- Ensures type-safe interactions with SQLite databases.

2. **SQLite Table Factory**
- Dynamic creation of SQLite tables with custom schemas.
- CRUD operation utilities for database operations.

3. **Debugging and Foreign Key Support**
- Debugging options for logging and troubleshooting.
- Management options for foreign keys within SQLite tables.

---

## Usage Examples

### Defining a SQLite Schema and Corresponding TypeScript Type

```typescript
import { SchemaMap } from '@bnk/core/modules/sqlite/sqlite-factory';

const noteSchema = {
id: { type: "TEXT" },
text: { type: "TEXT" }
} satisfies SchemaMap;

// TypeScript type is automatically inferred from the schema
type Note = SQLiteSchemaInfer<typeof noteSchema>;
```

### Creating and Using a Table with the Inferred TypeScript Type

```typescript
import { createSqliteFactory, SQLiteSchemaInfer } from '@bnk/core/modules/sqlite';

const db = new Database("path/to/database");
const { dbTableFactory } = createSqliteFactory({ db });

const notesTable = dbTableFactory({
schema: noteSchema,
tableName: "notes",
});

// Using the table with TypeScript type safety
notesTable.create({ id: "1", text: "Note text" });
```

---

## Integrating SQLite with Server Module

You can integrate the SQLite module with the server module for dynamic web applications. For example, use SQLite for storing and retrieving data in server routes:

```typescript
import { serverFactory } from '@bnk/core/modules/server';
import { createSqliteFactory } from '@bnk/core/modules/sqlite';

const db = new Database("path/to/database");
const { dbTableFactory } = createSqliteFactory({ db });
const notesTable = dbTableFactory({ schema: noteSchema, tableName: "notes" });

const routes = {
"/notes": {
GET: async () => {
const notes = await notesTable.readAll();
return new Response(JSON.stringify(notes), { headers: { "Content-Type": "application/json" } });
},
POST: async (req) => {
const note = await req.json();
await notesTable.create(note);
return new Response("Note created", { status: 201 });
}
}
};

const { start } = serverFactory({ routes });
start();
```

### Migrations - Coming Soon

For migrations, consider creating a separate script that reads your current database schema, compares it with the new schema, and executes the necessary ALTER TABLE commands. This script can be run manually or as part of your deployment process.

---

## Summary

The SQLite Module in the Bun Nook Kit empowers developers to build type-safe, SQLite-backed applications with TypeScript. By leveraging TypeScript's type inference, it ensures a seamless and error-free interaction with SQLite databases. This module, when combined with the server module, allows for the creation of robust, data-driven web applications.

0 comments on commit 22b837d

Please sign in to comment.