Hcs.Assigns
hcs · API reference
Type-safe per-request storage.
Plugs can attach typed values to a request and downstream handlers can read them without stringly-typed lookup or casts.
Example:
let current_user : user Hcs.Assigns.key = Hcs.Assigns.create_key () in
let assigns = Hcs.Assigns.add current_user user (Hcs.Request.assigns req) in
let req = { req with Hcs.Server.assigns = assigns } in
match Hcs.Assigns.find current_user (Hcs.Request.assigns req) with
| Some user -> ...
| None -> ...Type-safe assignable values attached to each request.
Assigns provides a heterogeneous map where each key is phantom-typed. Plugs store data here using add, and handlers (or downstream plugs) retrieve it with find.
Each project registers its own typed keys with create_key:
module My_keys = struct
let user : User.t Hcs.Assigns.key = Hcs.Assigns.create_key ()
let request_id : string Hcs.Assigns.key = Hcs.Assigns.create_key ()
endIn a plug:
let req =
{ req with assigns = Hcs.Assigns.add My_keys.user user req.assigns }In a handler:
match Hcs.Assigns.find My_keys.user req.assigns with
| Some user -> ...
| None -> ...Core Types
type 'a keyPhantom-typed key for storing typed values in t.
type bindingA single binding in the map: some type paired with its phantom-typed key and value.
type tThe assigns map itself — an opaque type of bindings.
Operations
val create_key : unit -> 'a keyA unique phantom-typed key.
Each call returns a key with a unique identity; use it to add and find values of the key's type.
val empty : tThe empty assigns map.
val add : 'a key -> 'a -> t -> tadd k v t associates value v with key k, returning the updated map. Adding the same key multiple times pushes a new binding; find returns the most recent.
val find : 'a key -> t -> 'a optionfind k t returns the most recent value associated with key k, or None if the key has never been added.