RequestContext
RequestContext
The RequestContext holds information relevant to the current request, which may be required at various points of the stack.
It is a good practice to inject the RequestContext (using the Ctx decorator) into all resolvers & REST handlers, and then pass it through to the service layer.
This allows the service layer to access information about the current user, the active language, the active Channel, and so on. In addition, the TransactionalConnection relies on the presence of the RequestContext object in order to correctly handle per-request database transactions.
Example
@Query()
myQuery(@Ctx() ctx: RequestContext) {
return this.myService.getData(ctx);
}
Signature
class RequestContext {
static empty() => RequestContext;
static deserialize(ctxObject: SerializedRequestContext) => RequestContext;
serialize() => SerializedRequestContext;
copy() => RequestContext;
req: Request | undefined
apiType: ApiType
channel: Channel
channelId: ID
languageCode: LanguageCode
session: CachedSession | undefined
activeUserId: ID | undefined
isAuthorized: boolean
authorizedAsOwnerOnly: boolean
translate(key: string, variables?: { [k: string]: any }) => string;
}
Members
empty
static method
type:
() => RequestContext
Creates an “empty” RequestContext object. This is only intended to be used
when a service method must be called outside the normal request-response
cycle, e.g. when programmatically populating data.
deserialize
static method
type:
(ctxObject: SerializedRequestContext) => RequestContext
Creates a new RequestContext object from a serialized object created by the
serialize()
method.
serialize
method
type:
() => SerializedRequestContext
Serializes the RequestContext object into a JSON-compatible simple object.
This is useful when you need to send a RequestContext object to another
process, e.g. to pass it to the Worker process via the WorkerService.
copy
method
type:
() => RequestContext
Creates a shallow copy of the RequestContext instance. This means that
mutations to the copy itself will not affect the original, but deep mutations
(e.g. copy.channel.code = ‘new’) will also affect the original.
req
property
type:
Request | undefined
The raw Express request object.
apiType
property
type:
ApiType
Signals which API this request was received by, e.g.
admin
or shop
.
channel
property
type:
Channel
The active Channel of this request.
channelId
property
type:
ID
languageCode
property
type:
LanguageCode
session
property
type:
CachedSession | undefined
activeUserId
property
type:
ID | undefined
isAuthorized
property
type:
boolean
True if the current session is authorized to access the current resolver method.
authorizedAsOwnerOnly
property
type:
boolean
True if the current anonymous session is only authorized to operate on entities that
are owned by the current session.
translate
method
type:
(key: string, variables?: { [k: string]: any }) => string
Translate the given i18n key