Current section

Files

Jump to
dream src dream@context.erl
Raw

src/dream@context.erl

-module(dream@context).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/dream/context.gleam").
-export([new_context/1]).
-export_type([app_context/0]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
?MODULEDOC(
" Request context for your application\n"
"\n"
" Context holds per-request data that changes with every request—user authentication,\n"
" session info, request IDs, etc. It's passed to every middleware and controller.\n"
"\n"
" ## The Default Context\n"
"\n"
" Dream provides `AppContext` with just a `request_id` field. It's fine for simple apps,\n"
" but most applications will want their own context type.\n"
"\n"
" ## Custom Context\n"
"\n"
" Define your own context type to hold whatever per-request data you need:\n"
"\n"
" ```gleam\n"
" pub type MyContext {\n"
" MyContext(\n"
" request_id: String,\n"
" user: Option(User),\n"
" session: Session,\n"
" permissions: List(String),\n"
" )\n"
" }\n"
" ```\n"
"\n"
" Then pass it to your server:\n"
"\n"
" ```gleam\n"
" dream.new()\n"
" |> dream.context(MyContext(\n"
" request_id: \"\",\n"
" user: None,\n"
" session: empty_session(),\n"
" permissions: []\n"
" ))\n"
" |> dream.services(my_services)\n"
" |> dream.router(my_router)\n"
" |> dream.listen(3000)\n"
" ```\n"
"\n"
" ## Enriching Context in Middleware\n"
"\n"
" Middleware can update the context as requests flow through:\n"
"\n"
" ```gleam\n"
" pub fn auth_middleware(request, context, services, next) {\n"
" case extract_token(request) {\n"
" Ok(token) -> {\n"
" let user = verify_token(services.db, token)\n"
" let new_context = MyContext(..context, user: Some(user))\n"
" next(request, new_context, services)\n"
" }\n"
" Error(_) -> unauthorized_response()\n"
" }\n"
" }\n"
" ```\n"
"\n"
" The type system ensures your controllers receive the right context type.\n"
).
-type app_context() :: {app_context, binary()}.
-file("src/dream/context.gleam", 72).
?DOC(
" Create a new AppContext\n"
"\n"
" Helper for creating the default context. If you're using a custom context,\n"
" you'll create it directly without this function.\n"
).
-spec new_context(binary()) -> app_context().
new_context(Request_id) ->
{app_context, Request_id}.