Skip to main content

Payload Introduction - JS/TS

A payload in logic is a object containing metadata and incoming data from a LOC trigger (for example, an API route).

Logic TypeAvailable
Generic logic
Aggregator logic

All tasks in the same execution receive the same trigger metadata and payload.

Import and Usage

export async function run(ctx) {
const payload = await ctx.payload();
}

export async function handleError(ctx, error) {
// ... same
}

Class Reference

Type

Trigger TypePayload TypeReference
API Route{ http: HttpPayload }HttpPayload
Message Queue{ messageQueue: MessagePayload }MessageQueuePayload
Schedule{ event: {} }Schedule payload (empty object)
Event{ event: EventPayload }Event payload (not yet implemented)

See the refered sub types for details.

Examples

Payload Type Assertion

To explicitly mark the payload type for editors supporting IntelliSense using JSDoc or TypeScript:

import {
HttpPayload,
GenericContext,
RailwayError,
} from "@fstnetwork/loc-logic-sdk";

export async function run(ctx: GenericContext) {
const payload = (await ctx.payload()) as { http: HttpPayload };
// or
// const payload: { http: HttpPayload } = await ctx.payload();
}

export async function handleError(ctx: GenericContext, error: RailwayError) {}
warning

Type assertions cannot prevent the payload getting set to a different type during execution and may thus cause runtime error.

Type Guard on Payload

If a logic may receive different types of payload, the safe way is to use a "type guard" to narrow it by checking the object key:

const payload = await ctx.payload();

let data = [];
if ("http" in payload) {
// narrowing payload to { http: HttpPayload }
data = payload.http.request.data;

} else if ("messageQueue" in payload) {
// narrowing payload to { messageQueue: MessagePayload }
data = payload.messageQueue.data;

} else {
// throw an error if the type is none of above
throw new Error("this logic only accepts http/mq payload");
}