Request (StrataRequest)
The StrataRequest class represents a request throughout its entire lifecycle -- from the moment it arrives to when the response is sent. It holds both the incoming request data and the outgoing response data. This is the object your operation handlers receive, and what middleware operates on.
import { StrataRequest } from '@strata-js/strata';
// Also exported as `Request` for convenience
import { Request } from '@strata-js/strata';Type Parameters
class StrataRequest<
PayloadType = Record<string, unknown>,
MetadataType = Record<string, unknown>,
ResponsePayloadType = Record<string, unknown>
>All three type parameters default to Record<string, unknown>.
Request Properties
These are set when the request is created and are read-only.
| Property | Type | Description |
|---|---|---|
id | string | Unique request identifier. |
context | string | Target context name. |
operation | string | Target operation name. |
payload | PayloadType | Application-specific request data. |
metadata | MetadataType | Additional metadata (tracking, stats, etc.). |
auth | string | undefined | Authentication data (typically a JWT). |
client | string | Human-readable client identifier. |
messageType | 'request' | 'post' | Whether this is a request (expects response) or a post (fire-and-forget). |
timestamp | string | ISO 8601 datetime of when the request was created. |
receivedTimestamp | number | Date.now() when the request was received by the service. |
responseQueue | string | undefined | Queue for sending the response (set by the backend). Only on requests, not posts. |
timeout | number | undefined | Timeout in milliseconds. Only on requests, not posts. |
priorRequest | string | undefined | ID of the request that triggered this one. |
requestChain | string[] | Chain of request IDs for distributed tracing. |
Response Properties
These are populated as the request is processed.
| Property | Type | Description |
|---|---|---|
status | 'pending' | 'succeeded' | 'failed' | Current request status. |
response | ResponsePayloadType | undefined | The response payload, set by succeed() or fail(). |
completedTimestamp | number | undefined | Date.now() when the request was completed. |
service | string | undefined | Identifier of the service that processed this. |
messages | ResponseMessage[] | Structured messages generated during processing. |
Internal Properties
| Property | Type | Description |
|---|---|---|
promise | Promise<void> | Resolves when the request is succeeded or failed. Used internally for tracking. |
Methods
succeed()
request.succeed(payload : ResponsePayloadType) : voidMarks the request as succeeded with the given payload. Sets status to 'succeeded', records the completedTimestamp, and resolves the internal promise.
// In an operation handler
context.registerOperation('get', async (request) =>
{
const user = await db.findUser(request.payload.userId);
request.succeed({ user });
});TIP
If your handler returns a value without calling succeed() or fail(), Strata automatically calls succeed() with the return value.
fail()
request.fail(reason : string | Error | ResponsePayloadType) : voidMarks the request as failed. Sets status to 'failed', records the completedTimestamp, and resolves the internal promise. The reason determines the response payload:
| Reason Type | Behavior |
|---|---|
ServiceError | Serialized via toJSON() -- includes name, message, code, isSafeMessage, stack. |
Error | Wrapped into { message, name: 'FailedRequestError', stack, code, details, isSafeMessage }. |
string | Wrapped into { message: reason, name: 'FailedRequestError', code: 'FAILED_REQUEST' }. |
object | Used directly as the response payload. |
// Fail with a string
request.fail('User not found');
// Fail with an Error
request.fail(new Error('Database connection lost'));
// Fail with a ServiceError (includes isSafeMessage for client-visible errors)
import { errors } from '@strata-js/strata';
request.fail(new errors.ServiceError('User not found', 'USER_NOT_FOUND'));
// Fail with a custom payload
request.fail({ message: 'Validation failed', errors: [ 'name is required' ] });renderRequest()
request.renderRequest() : RequestEnvelope<PayloadType, MetadataType>Serializes the request into its wire format -- a plain RequestEnvelope object with no methods. Useful for logging, debugging, or creating clones.
const envelope = request.renderRequest();
console.log(JSON.stringify(envelope, null, 2));renderResponse()
request.renderResponse() : ResponseEnvelope<ResponsePayloadType>Serializes the response into its wire format -- a plain ResponseEnvelope object with no methods.
const envelope = request.renderResponse();
console.log(envelope.status); // 'succeeded' or 'failed'
console.log(envelope.payload); // the response payload
console.log(envelope.messages); // any ResponseMessage objectsparseResponse()
request.parseResponse(response : ResponseEnvelope<ResponsePayloadType>) : voidPopulates this request's response properties from a received ResponseEnvelope. Used internally by the client when a response arrives over the wire. Calls succeed() or fail() based on the envelope's status.
Working with Messages
The messages array on a request holds ResponseMessage objects. You can push messages onto this array during processing to include warnings, info, or debug details in the response -- even on successful requests.
context.registerOperation('create', async (request) =>
{
const user = await db.createUser(request.payload);
if(user.emailUnverified)
{
request.messages.push({
severity: 'warning',
message: 'Email address has not been verified.',
code: 'EMAIL_UNVERIFIED',
});
}
return { user };
});See ResponseMessage for the full interface.
Lifecycle
- A request arrives and a
StrataRequestis constructed withstatus: 'pending'. - Global
beforeRequest()middleware runs. - Context
beforeRequest()middleware runs. - Operation
beforeRequest()middleware runs. - If still
'pending', the operation handler executes. - If the handler returns a value and the request is still
'pending',succeed()is called with the return value. - If the request succeeded,
success()middleware runs (operation -> context -> global). - If the request failed,
failure()middleware runs (operation -> context -> global). - The response is rendered and sent back via the backend.
At any point, middleware can short-circuit by calling request.succeed() or request.fail() directly. See Middleware Model for details.