### Complete Workflow Example - Onboarding (TypeScript) Source: https://queuebear.com/llm A comprehensive example of a QueueBear workflow for user onboarding. It defines input types and demonstrates the use of the `serve` function to execute workflow steps, with automatic caching for tasks like sending welcome emails. ```typescript // app/api/workflows/onboarding/route.ts import { serve } from "queuebear"; interface OnboardingInput { userId: string; email: string; } export const POST = serve( async (context) => { const { userId, email } = context.input; // Step 1: Send welcome email (cached if already done) ``` -------------------------------- ### Workflow Execution Example - JavaScript Source: https://queuebear.com/llm Demonstrates a simple workflow execution using QueueBear's context API. This example shows how to run tasks sequentially, including sending an email and sleeping for a specified duration, within a defined workflow. ```javascript await context.run("send-welcome", async () => { await sendEmail(email, "welcome"); }); // Step 2: Wait 3 days await context.sleep("wait-3-days", 60 * 60 * 24 * 3); // Step 3: Send tips email await context.run("send-tips", async () => { await sendEmail(email, "tips"); }); ``` -------------------------------- ### GET /v1/projects/:projectId/workflows/runs/{runId} Source: https://queuebear.com/llm Retrieves detailed information about a specific workflow run, including its status, input, output, and the status of each step within the workflow. ```APIDOC ## GET /v1/projects/:projectId/workflows/runs/{runId} ### Description Retrieves detailed information about a specific workflow run, including its status and the status of its individual steps. ### Method GET ### Endpoint /v1/projects/:projectId/workflows/runs/{runId} ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. - **runId** (string) - Required - The ID of the workflow run to retrieve. #### Query Parameters None #### Request Body None ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **id** (string) - The ID of the workflow run. - **workflowId** (string) - The ID of the workflow. - **status** (string) - The overall status of the run (e.g., 'pending', 'running', 'completed', 'failed'). - **input** (object) - The input data provided to the run. - **output** (any) - The output of the workflow run, if completed. - **createdAt** (string) - Timestamp when the run was created. - **completedAt** (string) - Timestamp when the run was completed (null if not completed). - **steps** (array) - An array of objects detailing each step in the workflow. - **stepName** (string) - The name of the step. - **stepIndex** (integer) - The order of the step. - **stepType** (string) - The type of step (e.g., 'run', 'sleep', 'call'). - **status** (string) - The status of the step. - **result** (any) - The result of the step, if completed. - **error** (any) - Any error information if the step failed. - **createdAt** (string) - Timestamp when the step started. - **completedAt** (string) - Timestamp when the step completed (null if not completed). ### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "workflowId": "user-onboarding", "status": "running", "input": { "userId": "123", "email": "user@example.com" }, "output": null, "createdAt": "2024-01-15T10:00:00Z", "completedAt": null, "steps": [ { "stepName": "send-welcome", "stepIndex": 0, "stepType": "run", "status": "completed", "result": { "sent": true }, "error": null, "createdAt": "2024-01-15T10:00:01Z", "completedAt": "2024-01-15T10:00:02Z" }, { "stepName": "wait-3-days", "stepIndex": 1, "stepType": "sleep", "status": "pending", "result": null, "error": null, "createdAt": "2024-01-15T10:00:03Z", "completedAt": null } ] } ``` ``` -------------------------------- ### Publish Message with Delay using cURL Source: https://queuebear.com/llm Shows how to publish a message with a specified delay and retry count using a cURL command. This example highlights the direct API interaction, including the HTTP method, URL, headers, and the JSON payload containing destination, body, delay, and retries. ```bash curl -X POST "https://queuebear.example.com/v1/projects/proj_xxx/publish" \ -H "Authorization: Bearer qb_live_xxxxx" \ -H "Content-Type: application/json" \ -d '{ "destination": "https://api.example.com/webhook", "body": {"event": "reminder", "userId": "123"}, "delay": "1h", "retries": 3 }' ``` -------------------------------- ### Create Schedule using cURL Source: https://queuebear.com/llm Creates a new schedule using a cURL command. This example demonstrates sending a POST request to the QueueBear API endpoint for schedules, including authorization, content type, and a JSON payload with destination, cron, timezone, and body. Ensure to replace placeholders with your actual project and bearer token. ```bash curl -X POST "https://queuebear.example.com/v1/projects/proj_xxx/schedules" \ -H "Authorization: Bearer qb_live_xxxxx" \ -H "Content-Type: application/json" \ -d '{ "destination": "https://api.example.com/daily-job", "cron": "0 9 * * *", "timezone": "America/New_York", "body": "{\"type\": \"daily\"}" }' ``` -------------------------------- ### Trigger and Wait for Workflow with QueueBear SDK Source: https://queuebear.com/llm Triggers a new workflow and waits for its completion, returning the result. This is a convenient method for starting a workflow and immediately getting its outcome. It requires the workflow name, a callback URL, input data, and optional timeout settings. ```javascript const result = await qb.triggerAndWait( "user-onboarding", "https://your-app.com/api/workflows/onboarding", { userId: "123" }, { timeoutMs: 120000 } ); console.log(result.result); ``` -------------------------------- ### Get Completed Steps - Node.js Source: https://queuebear.com/llm Retrieves all completed steps from the context. This is useful for debugging and understanding workflow progression. It logs the total count of completed steps to the console. ```javascript const steps = await context.getCompletedSteps(); console.log(`Completed ${steps.length} steps`); ``` -------------------------------- ### GET /v1/projects/:projectId/workflows/{workflowId}/runs Source: https://queuebear.com/llm Retrieves a list of past and current runs for a specific workflow. You can filter the results by status and paginate through the list using `limit` and `offset` parameters. ```APIDOC ## GET /v1/projects/:projectId/workflows/{workflowId}/runs ### Description Retrieves a list of runs for a specific workflow. Supports filtering by status and pagination. ### Method GET ### Endpoint /v1/projects/:projectId/workflows/{workflowId}/runs ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. - **workflowId** (string) - Required - The ID of the workflow whose runs to list. #### Query Parameters - **status** (string) - Optional - Filter by status (e.g., 'pending', 'running', 'completed', 'failed'). - **limit** (integer) - Optional - Maximum number of results per page (1-100, default: 50). - **offset** (integer) - Optional - Pagination offset (default: 0). ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **runs** (array) - A list of workflow run objects. - **id** (string) - The ID of the workflow run. - **workflowId** (string) - The ID of the workflow. - **status** (string) - The current status of the run. - **input** (object) - The input data provided to the run. - **output** (any) - The output of the workflow run, if completed. - **createdAt** (string) - Timestamp when the run was created. - **completedAt** (string) - Timestamp when the run was completed (null if not completed). - **pagination** (object) - Pagination details. - **limit** (integer) - The limit used for this page. - **offset** (integer) - The offset used for this page. - **hasMore** (boolean) - Indicates if there are more results available. #### Response Example ```json { "runs": [ { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "workflowId": "user-onboarding", "status": "running", "input": { "userId": "123" }, "output": null, "createdAt": "2024-01-15T10:00:00Z", "completedAt": null } ], "pagination": { "limit": 50, "offset": 0, "hasMore": false } } ``` ``` -------------------------------- ### Get Schedule Source: https://queuebear.com/llm Retrieves the details of a specific schedule by its ID. ```APIDOC ## GET /v1/projects/:projectId/schedules/:scheduleId ### Description Retrieves the details of a specific schedule. ### Method GET ### Endpoint /v1/projects/:projectId/schedules/:scheduleId ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. - **scheduleId** (string) - Required - The ID of the schedule to retrieve. ### Response #### Success Response (200) Includes all schedule details (destination, cron, timezone, method, retries, isActive, isPaused, lastExecutedAt, nextExecutionAt, executionCount, failureCount, createdAt) plus body, headers, and metadata. #### Response Example (Response structure is similar to the 'List Schedules' response but includes additional fields like body, headers, and metadata if they were set during creation.) ```json { "scheduleId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "destination": "https://api.example.com/cron-job", "cron": "0 9 * * *", "timezone": "America/New_York", "method": "POST", "body": "{\"type\": \"daily-report\"}", "headers": { "Content-Type": "application/json" }, "retries": 3, "isActive": true, "isPaused": false, "lastExecutedAt": "2024-01-15T14:00:00Z", "nextExecutionAt": "2024-01-16T14:00:00Z", "executionCount": 42, "failureCount": 2, "createdAt": "2024-01-01T10:00:00Z" } ``` ``` -------------------------------- ### GET /v1/projects/:projectId/dlq/{dlqId} Source: https://queuebear.com/llm Retrieves a specific Dead Letter Queue (DLQ) entry by its ID. The response includes details about the original message, attempts made, and recovery status. ```APIDOC ## GET /v1/projects/:projectId/dlq/{dlqId} ### Description Retrieves a specific Dead Letter Queue (DLQ) entry by its ID. The response includes details about the original message, attempts made, and recovery status. ### Method GET ### Endpoint /v1/projects/:projectId/dlq/{dlqId} ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. - **dlqId** (string) - Required - The ID of the DLQ entry to retrieve. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **id** (string) - The unique identifier for the DLQ entry. - **originalMessageId** (string) - The ID of the original message. - **destination** (string) - The intended destination of the message. - **method** (string) - The HTTP method used for the original request. - **body** (object) - The body of the original message. - **headers** (object) - The headers of the original message. - **failureReason** (string) - The reason for the message being sent to the DLQ. - **lastStatusCode** (integer) - The HTTP status code of the last failed attempt. - **totalAttempts** (integer) - The total number of attempts made to process the message. - **lastAttemptAt** (string) - The timestamp of the last processing attempt. - **recoveredAt** (string) - The timestamp when the message was recovered. - **recoveryMessageId** (string) - The ID of the message after recovery. - **createdAt** (string) - The timestamp when the DLQ entry was created. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "originalMessageId": "msg_12345", "destination": "/api/handler", "method": "POST", "body": { "key": "value" }, "headers": { "Content-Type": "application/json" }, "failureReason": "Internal Server Error", "lastStatusCode": 500, "totalAttempts": 3, "lastAttemptAt": "2023-10-27T10:00:00Z", "recoveredAt": null, "recoveryMessageId": null, "createdAt": "2023-10-27T09:00:00Z" } ``` ``` -------------------------------- ### Publish Message Locally via Tunnelmole - Node.js Source: https://queuebear.com/llm Publishes a message using the QueueBear API, configured for local development with a Tunnelmole URL. This example demonstrates how to send messages to a webhook endpoint exposed via Tunnelmole, useful for testing callbacks. ```javascript await qb.messages.publish("https://xxxx.tunnelmole.com/api/webhooks", { event: "user.created", userId: "123" }); ``` -------------------------------- ### Trigger Workflow Locally via Tunnelmole - Node.js Source: https://queuebear.com/llm Triggers a workflow using the QueueBear API, configured for local development with a Tunnelmole URL. This example shows how to initiate a workflow that sends data to a local endpoint exposed by Tunnelmole. ```javascript await qb.workflows.trigger( "onboarding", "https://xxxx.tunnelmole.com/api/workflows/onboarding", { userId: "123" } ); ``` -------------------------------- ### Get Message Details with QueueBear SDK Source: https://queuebear.com/llm Retrieves the details of a specific message using its ID from the QueueBear SDK. It logs the message's status and its delivery logs. ```javascript const message = await qb.messages.get(messageId); console.log(message.status); console.log(message.deliveryLogs); ``` -------------------------------- ### Get Workflow Run Status - JavaScript SDK Source: https://queuebear.com/llm Fetches the status and step details of a specific workflow run using its ID via the QueueBear SDK. This allows developers to monitor the progress and outcomes of individual workflow executions, including any errors. ```javascript const status = await qb.workflows.getStatus(runId); console.log(status.status); console.log(status.steps); ``` -------------------------------- ### Trigger Workflow with QueueBear SDK (JavaScript) Source: https://queuebear.com/llm Demonstrates how to trigger a workflow using the QueueBear JavaScript SDK. This involves initializing the SDK with API credentials and then calling the trigger method with workflow details, input data, and an idempotency key. It also shows how to retrieve the workflow status and wait for its completion. ```javascript import { QueueBear } from "queuebear"; const qb = new QueueBear({ apiKey: "qb_live_xxxxx", projectId: "proj_xxx", }); // Trigger workflow const { id } = await qb.workflows.trigger( "user-onboarding", "https://your-app.com/api/workflows/onboarding", { userId: "123", email: "user@example.com" }, { idempotencyKey: "onboarding-user-123" } ); // Check status const status = await qb.workflows.getStatus(id); console.log(status.status); // Wait for completion const result = await qb.workflows.waitForCompletion(id); ``` -------------------------------- ### List Schedules Source: https://queuebear.com/llm Retrieves a list of all schedules for a given project, with optional pagination. ```APIDOC ## GET /v1/projects/:projectId/schedules ### Description Retrieves a list of all schedules for a given project. ### Method GET ### Endpoint /v1/projects/:projectId/schedules ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. #### Query Parameters - **limit** (integer) - Optional - Max results per page (1-100, default: 50). - **offset** (integer) - Optional - Pagination offset (default: 0). ### Response #### Success Response (200) - **schedules** (array) - An array of schedule objects. - **scheduleId** (string) - The ID of the schedule. - **destination** (string) - The destination URL. - **cron** (string) - The cron expression. - **timezone** (string) - The timezone. - **method** (string) - The HTTP method. - **retries** (integer) - The number of retries. - **isActive** (boolean) - Whether the schedule is active. - **isPaused** (boolean) - Whether the schedule is paused. - **lastExecutedAt** (string) - The last execution time in ISO format. - **nextExecutionAt** (string) - The next execution time in ISO format. - **executionCount** (integer) - The total number of executions. - **failureCount** (integer) - The total number of failures. - **createdAt** (string) - The creation time in ISO format. - **pagination** (object) - Pagination details. - **limit** (integer) - The limit used for this page. - **offset** (integer) - The offset used for this page. - **hasMore** (boolean) - Indicates if there are more results. #### Response Example ```json { "schedules": [ { "scheduleId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "destination": "https://api.example.com/cron-job", "cron": "0 9 * * *", "timezone": "America/New_York", "method": "POST", "retries": 3, "isActive": true, "isPaused": false, "lastExecutedAt": "2024-01-15T14:00:00Z", "nextExecutionAt": "2024-01-16T14:00:00Z", "executionCount": 42, "failureCount": 2, "createdAt": "2024-01-01T10:00:00Z" } ], "pagination": { "limit": 50, "offset": 0, "hasMore": false } } ``` ``` -------------------------------- ### Workflow Context Methods Source: https://queuebear.com/llm Methods available within serve() handlers via the context parameter for executing and managing workflow steps. ```APIDOC ## Workflow Context Methods These methods are available within `serve()` handlers via the `context` parameter. ### `context.run(stepName, fn, options?)` #### Description Executes a step with automatic caching. If the workflow is retried, cached results are returned without re-executing. #### Parameters - **stepName** (string) - Required - A unique name for the step to enable caching. - **fn** (function) - Required - The asynchronous function to execute for the step. - **options** (object) - Optional - Options for the run step. #### Example ```javascript const result = await context.run("fetch-user", async () => { return await db.users.findById(userId); }); ``` ### `context.sleep(stepName, seconds)` #### Description Pauses the workflow for a specified duration in seconds. #### Parameters - **stepName** (string) - Required - A unique name for the sleep step. - **seconds** (number) - Required - The duration to pause in seconds. #### Example ```javascript await context.sleep("wait-1-hour", 3600); ``` ### `context.sleepUntil(stepName, date)` #### Description Pauses the workflow until a specific date and time. #### Parameters - **stepName** (string) - Required - A unique name for the sleep step. - **date** (Date) - Required - The specific date and time to pause until. #### Example ```javascript await context.sleepUntil("wait-until-tomorrow", new Date("2024-01-15")); ``` ### `context.call(stepName, config)` #### Description Makes an HTTP call as a cached step. #### Parameters - **stepName** (string) - Required - A unique name for the HTTP call step. - **config** (object) - Required - Configuration for the HTTP call (e.g., `url`, `method`, `headers`, `body`). #### Example ```javascript const data = await context.call("fetch-api", { url: "https://api.example.com/data", method: "POST", headers: { Authorization: "Bearer xxx" }, body: { key: "value" }, }); ``` ### `context.waitForEvent(stepName, eventName, options?)` #### Description Waits for an external event. The workflow pauses until `sendEvent()` is called with a matching `eventName` and optional `eventKey`. #### Parameters - **stepName** (string) - Required - A unique name for the wait event step. - **eventName** (string) - Required - The name of the event to wait for. - **options** (object) - Optional - Options for waiting for the event (e.g., `eventKey`, `timeoutSeconds`). #### Example ```javascript const payload = await context.waitForEvent("wait-approval", "order.approved", { eventKey: "order-123", timeoutSeconds: 86400, }); ``` ### `context.notify(eventName, payload?)` #### Description Sends a fire-and-forget event. This method does not wait for a response. #### Parameters - **eventName** (string) - Required - The name of the event to notify. - **payload** (object) - Optional - Data to send with the event. #### Example ```javascript await context.notify("user.onboarded", { userId: "123" }); ``` ### `context.parallel(steps)` #### Description Executes multiple steps in parallel. #### Parameters - **steps** (array) - Required - An array of step objects, each with a `name` and a `fn` (function). #### Example ```javascript const [user, orders, preferences] = await context.parallel([ { name: "fetch-user", fn: () => fetchUser(userId) }, { name: "fetch-orders", fn: () => fetchOrders(userId) }, { name: "fetch-preferences", fn: () => fetchPreferences(userId) }, ]); ``` ### `context.getCompletedSteps()` #### Description Returns a list of steps that have successfully completed within the current workflow run. #### Example ```javascript const completedSteps = context.getCompletedSteps(); ``` ``` -------------------------------- ### Get Message API Source: https://queuebear.com/llm Retrieves the details of a specific message using its ID. ```APIDOC ## GET /v1/projects/:projectId/messages/{messageId} ### Description Retrieves the details of a specific message by its unique ID. ### Method `GET` ### Endpoint `/v1/projects/:projectId/messages/{messageId}` ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. - **messageId** (string) - Required - The ID of the message to retrieve. ### Response #### Success Response (200) - **messageId** (string) - The unique ID of the message. - **destination** (string) - The destination URL for the message. - **method** (string) - The HTTP method used for delivery. - **body** (string) - The message payload, often JSON stringified. - **headers** (object) - Headers associated with the message. #### Response Example ```json { "messageId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "destination": "https://api.example.com/webhook", "method": "POST", "body": "{\"event\": \"user.created\"}", "headers": {} } ``` ``` -------------------------------- ### Get DLQ Entry Source: https://queuebear.com/llm Retrieves the details of a specific entry in the Dead Letter Queue (DLQ) by its ID. ```APIDOC ## GET /v1/projects/:projectId/dlq/:entryId ### Description Retrieves the details of a specific DLQ entry. ### Method GET ### Endpoint /v1/projects/:projectId/dlq/:entryId ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. - **entryId** (string) - Required - The ID of the DLQ entry to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique ID of the DLQ entry. - **originalMessageId** (string) - The ID of the original message that failed. - **destination** (string) - The destination URL the message was intended for. - **method** (string) - The HTTP method used for the failed request. - **body** (string) - The original request body. - **headers** (object) - The original request headers. - **failureReason** (string) - The reason for the failure. - **lastStatusCode** (integer) - The HTTP status code of the last failed attempt. - **totalAttempts** (integer) - The total number of attempts made. - **lastAttemptAt** (string) - The timestamp of the last attempt in ISO format. - **createdAt** (string) - The timestamp when the entry was added to DLQ in ISO format. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "originalMessageId": "b2c3d4e5-f678-9012-bcde-f12345678901", "destination": "https://api.example.com/webhook", "method": "POST", "body": "{\"type\": \"daily-report\"}", "headers": { "Content-Type": "application/json" }, "failureReason": "Connection timeout", "lastStatusCode": 504, "totalAttempts": 4, "lastAttemptAt": "2024-01-15T10:05:00Z", "createdAt": "2024-01-15T10:00:00Z" } ``` ``` -------------------------------- ### Initialize QueueBear TypeScript Client Source: https://queuebear.com/llm Initializes the QueueBear client using your API key and project ID. This client is then used to interact with QueueBear's services via its SDK. ```typescript import { QueueBear } from "queuebear"; const qb = new QueueBear({ apiKey: "qb_live_xxx", projectId: "proj_xxx", }); ``` -------------------------------- ### Next.js App Router Workflow Integration Source: https://queuebear.com/llm Demonstrates how to integrate QueueBear's `serve` function within a Next.js App Router API route. It sets up a POST handler that executes a workflow, including running cached steps. ```typescript // app/api/workflows/my-workflow/route.ts import { serve } from "queuebear"; export const POST = serve(async (context) => { await context.run("step-1", async () => { /* ... */ }); return { success: true }; }); ``` -------------------------------- ### Local Development with Tunnelmole Source: https://queuebear.com/llm Guidance on using Tunnelmole to expose local webhook endpoints for testing with QueueBear during local development. ```APIDOC ## Security & Local Development: Local Development with Tunnelmole When developing locally, webhook endpoints run on `localhost`, which is not accessible from QueueBear's servers. Use Tunnelmole to expose your local server. ### Install Tunnelmole **Linux, macOS, Windows WSL:** ```bash curl -O https://install.tunnelmole.com/t357g/install && sudo bash install ``` **Node.js (all platforms, requires Node 16+):** ```bash npm install -g tunnelmole ``` ### Start a Tunnel ```bash tmole 3000 # Output: https://xxxx.tunnelmole.com is forwarding to localhost:3000 ``` ### Use the Tunnel URL ```javascript // For webhooks await qb.messages.publish("https://xxxx.tunnelmole.com/api/webhooks", { event: "user.created", userId: "123" }); // For workflows await qb.workflows.trigger( "onboarding", "https://xxxx.tunnelmole.com/api/workflows/onboarding", { userId: "123" } ); ``` **Tips:** - Store the tunnel URL in `.env` for easy switching between local and production. - Both `callbackUrl` and `failureCallbackUrl` need public URLs for local testing. - Tunnel URLs change on restart. ``` -------------------------------- ### Create Schedule using QueueBear SDK Source: https://queuebear.com/llm Creates a new schedule using the QueueBear SDK. This function takes a configuration object including destination URL, cron expression, timezone, HTTP method, request body, headers, retry count, and metadata. It returns the created schedule object. ```javascript const schedule = await qb.schedules.create({ destination: "https://api.example.com/cron-job", cron: "0 9 * * *", timezone: "America/New_York", method: "POST", body: JSON.stringify({ type: "daily-report" }), headers: { "Content-Type": "application/json" }, retries: 3, metadata: { jobName: "daily-report" }, }); ``` -------------------------------- ### Check Message Status using cURL Source: https://queuebear.com/llm Provides a cURL command to check the status of a specific message by its ID. This is a GET request to the /messages/{messageId} endpoint, requiring only the authorization header. ```bash curl "https://queuebear.example.com/v1/projects/proj_xxx/messages/a1b2c3d4-e5f6-7890-abcd-ef1234567890" \ -H "Authorization: Bearer qb_live_xxxxx" ``` -------------------------------- ### Hono Workflow Integration Source: https://queuebear.com/llm Illustrates the integration of QueueBear's `serve` function with the Hono web framework. It sets up a Hono route that uses the QueueBear handler to process workflow requests. ```typescript import { Hono } from "hono"; import { serve } from "queuebear"; const app = new Hono(); const handler = serve(async (context) => { await context.run("step-1", async () => { /* ... */ }); return { success: true }; }); app.post("/api/workflows/my-workflow", async (c) => { const response = await handler(c.req.raw); return response; }); ``` -------------------------------- ### Get Message Details via REST API Source: https://queuebear.com/llm Shows the structure of a REST API request to retrieve details of a specific message using its ID. This endpoint is useful for checking the status or content of a queued message. ```json { "messageId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "destination": "https://api.example.com/webhook", "method": "POST", "body": "{\"event\": \"user.created\"}", "headers": { ``` -------------------------------- ### Publish Message via cURL Source: https://queuebear.com/llm Demonstrates how to publish a message to QueueBear using a cURL command. This showcases the HTTP request structure, including the endpoint, headers, and JSON payload, for sending messages. ```bash curl -X POST "https://queuebear.example.com/v1/projects/proj_xxx/publish" \ -H "Authorization: Bearer qb_live_xxxxx" \ -H "Content-Type: application/json" \ -d '{ "destination": "https://api.example.com/webhook", "body": {"event": "user.created", "userId": "123"}, "delay": "30s", "retries": 5, "callbackUrl": "https://api.example.com/callback", "headers": { "X-Custom-Header": "value" } }' ``` -------------------------------- ### Create Schedule Source: https://queuebear.com/llm Creates a new scheduled job. You can specify the destination URL, cron schedule, timezone, HTTP method, and optionally include a request body, headers, retries, and metadata. ```APIDOC ## POST /v1/projects/:projectId/schedules ### Description Creates a new scheduled job. ### Method POST ### Endpoint /v1/projects/:projectId/schedules ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. #### Request Body - **destination** (string) - Required - The URL to send the request to. - **cron** (string) - Required - The cron expression for the schedule. - **timezone** (string) - Required - The timezone for the cron schedule. - **method** (string) - Optional - The HTTP method to use (e.g., POST, GET). Defaults to POST. - **body** (string) - Optional - The request body to send. Must be a JSON string. - **headers** (object) - Optional - Custom headers to include in the request. - **retries** (integer) - Optional - The number of times to retry the job if it fails. Defaults to 3. - **metadata** (object) - Optional - Additional metadata to associate with the schedule. ### Request Example ```json { "destination": "https://api.example.com/cron-job", "cron": "0 9 * * *", "timezone": "America/New_York", "method": "POST", "body": "{\"type\": \"daily-report\"}", "headers": { "Content-Type": "application/json" }, "retries": 3, "metadata": { "jobName": "daily-report" } } ``` ### Response #### Success Response (200) - **scheduleId** (string) - The ID of the created schedule. - **destination** (string) - The destination URL. - **cron** (string) - The cron expression. - **timezone** (string) - The timezone. - **method** (string) - The HTTP method. - **retries** (integer) - The number of retries. - **isActive** (boolean) - Whether the schedule is active. - **isPaused** (boolean) - Whether the schedule is paused. - **nextExecutionAt** (string) - The next execution time in ISO format. - **createdAt** (string) - The creation time in ISO format. #### Response Example ```json { "scheduleId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "destination": "https://api.example.com/cron-job", "cron": "0 9 * * *", "timezone": "America/New_York", "method": "POST", "retries": 3, "isActive": true, "isPaused": false, "nextExecutionAt": "2024-01-16T14:00:00Z", "createdAt": "2024-01-15T10:00:00Z" } ``` ``` -------------------------------- ### Authentication Source: https://queuebear.com/llm Details on how to authenticate with the QueueBear API using API keys and the base URL. ```APIDOC ## Authentication ### Description All API routes are prefixed with `/v1/projects/:projectId`. You must include your API key in the `Authorization` header as a Bearer token. ### Base URL `https://your-queuebear-instance.com` ### Authorization Header `Authorization: Bearer qb_live_xxxxxxxxxxxxx` ### API Key Types * `qb_live_*`: Production environment, live traffic. * `qb_test_*`: Testing environment, development/testing. ### Permissions * `publish`: Create messages, schedules; modify/delete resources. * `read`: Read messages, schedules, DLQ entries. ``` -------------------------------- ### POST /v1/projects/{projectId}/publish Source: https://queuebear.com/llm Publishes a message to a specified destination. Allows for setting delays and retries. ```APIDOC ## POST /v1/projects/{projectId}/publish ### Description Publishes a message to a specified destination. Allows for setting delays and retries. ### Method POST ### Endpoint `/v1/projects/{projectId}/publish` ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. #### Request Body - **destination** (string) - Required - The URL to send the message to. - **body** (object) - Required - The payload of the message. - **delay** (string) - Optional - The delay before sending the message (e.g., '10m', '2h'). - **retries** (number) - Optional - The number of times to retry sending the message if it fails. ### Request Example ```javascript async function publishMessage( projectId: string, destination: string, body: object, options?: { delay?: string; retries?: number } ) { const response = await fetch( `https://queuebear.example.com/v1/projects/${projectId}/publish`, { method: "POST", headers: { Authorization: "Bearer qb_live_xxxxx", "Content-Type": "application/json", }, body: JSON.stringify({ destination, body, delay: options?.delay, retries: options?.retries, }), } ); return response.json(); } const { messageId } = await publishMessage( "proj_xxx", "https://api.example.com/webhook", { event: "user.created", userId: "123" }, ); ``` -------------------------------- ### Get DLQ Entry by ID - QueueBear SDK Source: https://queuebear.com/llm Retrieves a specific Dead Letter Queue (DLQ) entry using its ID. This function returns an object containing details of the DLQ entry, including its body and attempt count. It is part of the QueueBear SDK's DLQ management capabilities. ```javascript const entry = await qb.dlq.get(dlqId); console.log(entry.body); console.log(entry.totalAttempts); ``` -------------------------------- ### Create Schedule Source: https://queuebear.com/llm Create a scheduled job to send a message at a specific time based on a cron expression. ```APIDOC ## POST /v1/projects/{projectId}/schedules ### Description Creates a schedule for sending messages. The message will be sent to the specified destination at times defined by the cron expression and timezone. ### Method POST ### Endpoint `/v1/projects/{projectId}/schedules` ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. #### Query Parameters None #### Request Body - **destination** (string) - Required - The URL where the message should be sent. - **cron** (string) - Required - The cron expression defining the schedule (e.g., "0 9 * * *"). - **timezone** (string) - Required - The timezone for the cron expression (e.g., "America/New_York"). - **body** (string) - Optional - The payload of the message. This should be a JSON string. ### Request Example ```json { "destination": "https://api.example.com/daily-job", "cron": "0 9 * * *", "timezone": "America/New_York", "body": "{\"type\": \"daily\"}" } ``` ### Response #### Success Response (200) - **scheduleId** (string) - The ID of the created schedule. #### Response Example ```json { "scheduleId": "sched_abcdef12345" } ``` ``` -------------------------------- ### Create Workflow Endpoint - Serve Function (TypeScript) Source: https://queuebear.com/llm Creates an HTTP handler for a workflow using the `serve` function from the QueueBear SDK. This function allows defining workflow logic that handles step caching and resumption automatically. It takes a handler function and optional ServeOptions. ```typescript import { serve } from "queuebear"; export const POST = serve(async (context) => { // Your workflow logic here return result; }, options); ``` -------------------------------- ### Execute Steps in Parallel with context.parallel Source: https://queuebear.com/llm Executes multiple workflow steps concurrently. This can significantly speed up workflows by running independent tasks in parallel. It requires an array of step objects, each with a name and a function to execute. ```javascript const [user, orders, preferences] = await context.parallel([ { name: "fetch-user", fn: () => fetchUser(userId) }, { name: "fetch-orders", fn: () => fetchOrders(userId) }, { name: "fetch-preferences", fn: () => fetchPreferences(userId) }, ]); ``` -------------------------------- ### List Schedules using QueueBear SDK Source: https://queuebear.com/llm Retrieves a list of schedules using the QueueBear SDK. This function can optionally accept query parameters for pagination, such as `limit` and `offset`. It returns an object containing an array of schedule objects and pagination details. ```javascript const { schedules } = await qb.schedules.list(); ``` -------------------------------- ### Execute Cached Step with context.run Source: https://queuebear.com/llm Executes a function as a step within a workflow, with automatic caching of results. If the workflow is retried, cached results are returned without re-executing the function. This requires a step name and the function to execute. ```javascript const result = await context.run("fetch-user", async () => { return await db.users.findById(userId); }); ``` -------------------------------- ### Signature Verification Source: https://queuebear.com/llm Instructions on how to verify that workflow requests originate from your QueueBear instance using a signing secret. ```APIDOC ## Security & Local Development: Signature Verification Verify that workflow requests come from your QueueBear instance: ```javascript export const POST = serve(handler, { signingSecret: process.env.QUEUEBEAR_SIGNING_SECRET, }); ``` The `signingSecret` is available in your QueueBear project settings. When configured, requests without a valid signature are rejected with a `401` status code. ``` -------------------------------- ### Publish Message with QueueBear Python Client Source: https://queuebear.com/llm Illustrates how to publish a message using a Python function that interacts with the QueueBear API. The function accepts project ID, destination, message body, and optional delay and retry parameters. It constructs the necessary headers and JSON payload for the POST request. ```python import requests def publish_message(project_id: str, destination: str, body: dict, delay: str = None, retries: int = None): response = requests.post( f"https://queuebear.example.com/v1/projects/{project_id}/publish", headers={ "Authorization": "Bearer qb_live_xxxxx", "Content-Type": "application/json", }, json={ "destination": destination, "body": body, "delay": delay, "retries": retries, } ) return response.json() result = publish_message( "proj_xxx", "https://api.example.com/webhook", {"event": "user.created", "userId": "123"}, delay="10s", retries=5 ) print(result["messageId"]) ``` -------------------------------- ### Publish Message - Node.js/TypeScript (Fetch API) Source: https://queuebear.com/llm Publishes a message to the QueueBear API using the Fetch API. This is the recommended method for sending messages, allowing configuration of destination, body, delay, and retries. It requires project ID, destination URL, and message body. ```typescript async function publishMessage( projectId: string, destination: string, body: object, options?: { delay?: string; retries?: number } ) { const response = await fetch( `https://queuebear.example.com/v1/projects/${projectId}/publish`, { method: "POST", headers: { Authorization: "Bearer qb_live_xxxxx", "Content-Type": "application/json", }, body: JSON.stringify({ destination, body, delay: options?.delay, retries: options?.retries, }), } ); return response.json(); } const { messageId } = await publishMessage( "proj_xxx", "https://api.example.com/webhook", { event: "user.created", userId: "123" }, ); ``` -------------------------------- ### Express Workflow Integration Source: https://queuebear.com/llm Shows how to integrate QueueBear's `serve` function with an Express.js application. It creates an Express route that acts as a workflow endpoint, forwarding requests to the QueueBear handler and returning the response. ```typescript import express from "express"; import { serve } from "queuebear"; const app = express(); app.use(express.json()); const handler = serve(async (context) => { await context.run("step-1", async () => { /* ... */ }); return { success: true }; }); app.post("/api/workflows/my-workflow", async (req, res) => { const response = await handler( new Request(req.url, { method: "POST", headers: req.headers as HeadersInit, body: JSON.stringify(req.body), }) ); res.status(response.status).json(await response.json()); }); ```