### Gleam Session Management Setup and Operations
Source: https://context7.com/glimr-org/framework/llms.txt
Demonstrates how to set up and use server-side sessions in Gleam, including storing and retrieving user data, regenerating session IDs, invalidating sessions, and utilizing flash messages for notifications and form repopulation.
```gleam
import glimr/session/session.{type Session}
// Setup session store at application boot
pub fn main() {
session.setup(session.cookie_store())
// Or use database/redis/file stores via adapters
}
// Basic session operations
pub fn login(ctx: Context(App), user_id: Int) -> Response {
// Store data in session
session.put(ctx.session, "user_id", int.to_string(user_id))
// Regenerate session ID after login (prevents session fixation)
session.regenerate(ctx.session)
redirect.to("/dashboard")
}
pub fn logout(ctx: Context(App)) -> Response {
// Destroy session completely
session.invalidate(ctx.session)
redirect.to("/")
}
pub fn get_current_user(ctx: Context(App)) -> Result(Int, Nil) {
case session.get(ctx.session, "user_id") {
Ok(id_str) -> int.parse(id_str)
Error(_) -> Error(Nil)
}
}
// Flash messages for one-time notifications
pub fn update_profile(ctx: Context(App)) -> Response {
// ... update logic
session.flash(ctx.session, "success", "Profile updated!")
redirect.to("/profile")
}
// In template or controller, read flash (automatically cleared after read)
pub fn show_profile(ctx: Context(App)) -> Response {
let success_message = session.get_flash(ctx.session, "success")
let has_success = session.has_flash(ctx.session, "success")
// ...
}
// Form repopulation after validation errors
// Validator automatically flashes old input as "old.{field}"
pub fn get_old_email(ctx: Context(App)) -> String {
session.old(ctx.session, "email") // Returns "" if not set
}
// Validation errors flashed as "errors.{field}"
pub fn get_email_error(ctx: Context(App)) -> String {
session.error(ctx.session, "email")
}
pub fn has_email_error(ctx: Context(App)) -> Bool {
session.has_error(ctx.session, "email")
}
```
--------------------------------
### Utilize Unified Caching API in Gleam
Source: https://context7.com/glimr-org/framework/llms.txt
Provides examples of basic cache operations like put, get, and delete, as well as advanced patterns like 'remember' for expensive computations and 'remember_json' for automatic serialization.
```gleam
import glimr/cache/cache.{type CachePool}
pub fn cache_example(pool: CachePool) {
let _ = cache.put(pool, "user:123", user_json, ttl_seconds: 3600)
case cache.get(pool, "user:123") {
Ok(value) -> decode_user(value)
Error(cache.NotFound) -> load_from_db()
Error(_) -> handle_error()
}
}
pub fn get_user_stats(pool: CachePool, user_id: Int) -> String {
cache.remember(pool, "stats:" <> int.to_string(user_id), ttl_seconds: 300, fn() {
compute_expensive_stats(user_id)
})
}
```
--------------------------------
### Generate HTTP Responses
Source: https://context7.com/glimr-org/framework/llms.txt
Provides examples of various response types including HTML, JSON, error pages, and custom headers using Glimr response helpers.
```gleam
pub fn show_page(ctx: Context(App)) -> Response {
response.html("
Hello World
", 200)
}
pub fn list_users(ctx: Context(App)) -> Response {
json.object([#("users", json.array(users, fn(u) { json.object([#("id", json.int(u.id))]) }))])
|> response.json(200)
}
pub fn download(ctx: Context(App)) -> Response {
response.html(content, 200)
|> response.header("content-disposition", "attachment; filename=data.csv")
}
```
--------------------------------
### Implement and Apply Middleware
Source: https://context7.com/glimr-org/framework/llms.txt
Illustrates creating custom middleware for authentication and applying it inline within controller functions.
```gleam
pub fn auth_middleware(ctx: Context(App), next: Next(App)) -> Response {
case session.get(ctx.session, "user_id") {
Ok(_) -> next(ctx)
Error(_) -> response.error(401)
}
}
pub fn admin_dashboard(ctx: Context(App)) -> Response {
use ctx <- middleware.apply([auth_middleware, admin_check], ctx)
response.html("Admin Dashboard
", 200)
}
```
--------------------------------
### Configure and Execute Database Operations in Gleam
Source: https://context7.com/glimr-org/framework/llms.txt
Demonstrates how to configure PostgreSQL and SQLite connections, perform CRUD operations, and manage transactions with automatic retries. It also shows the usage of parameter helpers to ensure type safety when interacting with the database.
```gleam
import glimr/db/db.{type DbPool, type Connection}
import gleam/dynamic/decode
let config = db.postgres_config(
"postgresql://postgres:secret@localhost:5432/myapp",
pool_size: 10,
)
pub fn find_user(pool: DbPool, id: Int) -> Result(User, DbError) {
db.query_one(
pool,
"SELECT id, name, email FROM users WHERE id = $1",
[db.int(id)],
user_decoder(),
)
}
pub fn transfer_funds(pool: DbPool, from: Int, to: Int, amount: Int) -> Result(Nil, DbError) {
use conn <- db.transaction(pool, retries: 3)
use _ <- result.try(db.exec_with(conn,
"UPDATE accounts SET balance = balance - $1 WHERE id = $2",
[db.int(amount), db.int(from)],
))
Ok(Nil)
}
```
--------------------------------
### Gleam Console Command Definition and Execution
Source: https://context7.com/glimr-org/framework/llms.txt
Illustrates how to define and run console commands in Gleam, including basic commands with arguments and flags, commands with database access, and commands interacting with the cache.
```gleam
import glimr/console/command.{type Command, type Args, Argument, Flag, Option}
// Define a simple command
pub fn main() {
command.new()
|> command.description("Greet a user by name")
|> command.args([
Argument("name", "The name to greet"),
Flag("loud", "l", "Use uppercase"),
Option("prefix", "Greeting prefix", "Hello"),
])
|> command.handler(fn(args) {
let name = command.get_arg(args, "name")
let prefix = command.get_option(args, "prefix")
let loud = command.has_flag(args, "loud")
let greeting = prefix <> ", " <> name <> "!"
case loud {
True -> io.println(string.uppercase(greeting))
False -> io.println(greeting)
}
})
|> command.run()
}
// Command with database access (pool automatically managed)
pub fn main() {
command.new()
|> command.description("Export all users to CSV")
|> command.args([
Option("output", "Output file path", "users.csv"),
])
|> command.db_handler(fn(args, pool) {
let output = command.get_option(args, "output")
case db.query_all(pool, "SELECT * FROM users", [], user_decoder()) {
Ok(users) -> write_csv(output, users)
Error(e) -> io.println("Error: " <> debug.string(e))
}
})
|> command.run()
}
// Command with cache access
pub fn main() {
command.new()
|> command.description("Clear application cache")
|> command.cache_handler(fn(args, pool) {
case cache.flush(pool) {
Ok(_) -> io.println("Cache cleared!")
Error(_) -> io.println("Failed to clear cache")
}
})
|> command.run()
}
```
--------------------------------
### Initialize Request Context in Glimr
Source: https://context7.com/glimr-org/framework/llms.txt
Demonstrates how to define an application state type and initialize a new request context for handling incoming HTTP requests.
```gleam
import glimr/http/context.{type Context}
import glimr/http/http.{type Request}
pub type App {
App(db: DbPool, cache: CachePool)
}
pub fn handle_request(req: Request, app: App) -> Response {
let ctx = context.new(req, app)
router.handle(ctx, route_groups, kernel_handle)
}
```
--------------------------------
### Define Route Groups and Middleware
Source: https://context7.com/glimr-org/framework/llms.txt
Shows how to organize routes into groups with specific prefixes and middleware stacks for API and Web endpoints.
```gleam
import glimr/routing/router.{type RouteGroup, RouteGroup}
import glimr/http/kernel.{Web, Api}
pub fn route_groups() -> List(RouteGroup(Context(App))) {
[
RouteGroup(
prefix: "/api",
middleware_group: Api,
routes: api_routes,
),
RouteGroup(
prefix: "",
middleware_group: Web,
routes: web_routes,
),
]
}
```
--------------------------------
### Define Database Schemas with Glimr DSL
Source: https://context7.com/glimr-org/framework/llms.txt
Explains how to use the Glimr schema DSL to define tables, columns, indexes, and constraints. This DSL acts as the source of truth for migrations and provides a wide range of column types including UUIDs, JSON, and foreign keys.
```gleam
import glimr/db/schema
pub fn definition() {
schema.table("users", [
schema.id(),
schema.string("name"),
schema.string("email"),
schema.boolean("is_active") |> schema.default_bool(True),
schema.foreign("organization_id", "organizations")
|> schema.on_delete(schema.Cascade),
schema.timestamps(),
])
|> schema.indexes([
schema.unique(["email"]),
schema.index(["status", "is_active"])
])
}
```
--------------------------------
### Compiling Loom Templates in Gleam
Source: https://context7.com/glimr-org/framework/llms.txt
This snippet demonstrates how to locate and categorize template files using the Loom API. It distinguishes between components and standard pages to ensure proper compilation order.
```gleam
import glimr/loom/loom
let files = loom.find_files()
let components = loom.find_components(files)
let pages = loom.find_non_components(files)
let views_path = loom.views_path
let output_path = loom.output_path
```
--------------------------------
### Implement Declarative Form Validation in Gleam
Source: https://context7.com/glimr-org/framework/llms.txt
Demonstrates how to define validation rules for form fields and file uploads using the Glimr validator module. It shows the integration within a controller to handle automatic redirection on validation failure.
```gleam
import glimr/forms/validator.{type FormData, Required, Email, MinLength, MaxLength, Confirmed, Unique, In, Numeric, Between}
pub type RegistrationData { RegistrationData(name: String, email: String, password: String) }
fn rules(ctx: Context(App)) -> List(validator.Rule(Context(App))) {
[
validator.for("name", [Required, MinLength(2), MaxLength(100)]),
validator.for("email", [Required, Email, Unique(ctx.app.db, "users")]),
validator.for("password", [Required, MinLength(8), Confirmed("password_confirmation")]),
validator.for("age", [Numeric, Between(18, 120)]),
validator.for("role", [Required, In(["admin", "user", "guest")]),
]
}
pub fn store(ctx: Context(App)) -> Response {
use validated <- validator.run(ctx, rules, data, redirect.back(ctx))
create_user(ctx.app.db, validated)
session.flash(ctx.session, "success", "Account created!")
redirect.to("/login")
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.