Context
To make it easy to pass state between functions responding to a request,
Yggdrasil Server packages the original request, normalized parameters, options,
your app's context, utilities, and more in a single, shared YggdrasilServerContext
object
(commonly named ygg
).
Some Yggdrasil Server features (Yggdrasil Server Router and Conduit) have their own
state that they provide to you via an extended version of the YggdrasilServerContext
.
This extended version uses prototype-based inheritance so that methods implemented in
the original object continue to run there.
To make it so that you don't have to pass ygg
into every function you call, and to
ensure the correct context (base/extended) is being referenced, built-in functions
that live in the ygg
context object uses the this
keyword to access the context.
Additionally, functions that you add as top-level members to your app's context object
will be appropriately bound so that they can access the context through this
(the
Conduit server client requires this).
Please observe the following practices to avoid inadvertently breaking Yggdrasil Server's context:
Accessing context
Always use the ygg
variable passed to you, if provided to you by Yggdrasil Server.
While you can and should pass the ygg
variable to your own helper functions, you
should not use the base context object from a Conduit handler, for example (the Conduit
context provided by Yggdrasil Server should be used instead). Additionally, do not
store the ygg
variable outside or beyond the scope of a request.
Calling context-based functions
Always access context functions and members directly through the context object.
Do not store them in another variable, or the this
context will be broken.
For example, do throw ygg.status(400, "NOT_FOUND")
instead of
const status = ygg.status; throw status(400, "NOT_FOUND");
. Furthermore,
do not use .bind
, .apply
, or anything else that changes the this
context.
Using your own context-based functions
Any top-level member functions present in your app context will be automatically
bound to the appropriate context, so you can use this
inside them to access
the context without requiring a separate ygg
parameter.
Please note that this strategy is intended only
for accessing whatever context is available. If you specifically need a Conduit
context, for example, it is recommended to use an explicit ygg
parameter to
enforce that.