### Node.js / TypeScript Fetch Example Source: https://context7_llms Example of publishing a message using the `fetch` API in Node.js or TypeScript. ```APIDOC ## Complete Code Examples ### Node.js / TypeScript Using `fetch` (recommended): ```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" }, ); ``` ``` -------------------------------- ### Complete Workflow Example - QueueBear SDK Source: https://context7_llms A comprehensive example of a QueueBear workflow, including input types and step caching for sequential operations like sending emails. ```javascript // 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) ``` -------------------------------- ### Local Development with Tunnelmole Source: https://context7_llms Guide to using Tunnelmole for local development to expose local webhook endpoints to QueueBear's servers. ```APIDOC ### Local Development with Tunnelmole When developing locally, webhook endpoints run on localhost which isn't accessible from QueueBear's servers. Use Tunnelmole to expose your local server. Install Tunnelmole: Linux, macOS, Windows WSL: `curl -O https://install.tunnelmole.com/t357g/install && sudo bash install` Node.js (all platforms, requires Node 16+): `npm install -g tunnelmole` Start a tunnel: `tmole 3000` # Output: https://xxxx.tunnelmole.com is forwarding to localhost:3000 Use the tunnel URL: ```javascript await qb.messages.publish("https://xxxx.tunnelmole.com/api/webhooks", { event: "user.created", userId: "123" }); await qb.workflows.trigger( "onboarding", "https://xxxx.tunnelmole.com/api/workflows/onboarding", { userId: "123" } ); ``` **Tips:** - Store 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 ``` -------------------------------- ### Parallel Multi-Service Orchestration Source: https://context7_llms This example shows how to orchestrate multiple services in parallel using `ctx.parallel()`. This allows for concurrent execution of independent tasks (fetching user data, orders, and recommendations), improving overall workflow performance. ```typescript const [user, orders, recommendations] = await ctx.parallel([ { name: "fetch-user", fn: () => userService.get(userId) }, { name: "fetch-orders", fn: () => orderService.list(userId) }, { name: "fetch-recs", fn: () => recService.get(userId) }, ]); ``` -------------------------------- ### Idempotent Webhook Receiver Example Source: https://context7_llms Example of an idempotent webhook receiver for order processing to prevent duplicate entries. ```APIDOC ## POST /webhooks/order ### Description This endpoint receives webhook notifications for orders and ensures idempotency by checking if an order has already been processed before creating a new one. ### Method POST ### Endpoint /webhooks/order ### Parameters #### Request Body - **orderId** (string) - Required - The unique identifier for the order. ### Request Example ```json { "orderId": "123e4567-e89b-12d3-a456-426614174000" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - Optional - A message indicating the status (e.g., "Already processed"). #### Response Example ```json { "success": true, "message": "Already processed" } ``` ``` -------------------------------- ### QueueBear Workflow Step Execution Example Source: https://context7_llms Illustrates a sequence of operations within a QueueBear workflow, including sending a welcome email, pausing execution for a specified duration (3 days), and then sending a follow-up tips email. This demonstrates the use of `context.run` for executing tasks and `context.sleep` for introducing delays. ```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"); }); return { completed: true }; ``` -------------------------------- ### Implement Exactly-Once Step Execution with Caching Source: https://context7_llms This example illustrates how to achieve exactly-once step execution within a workflow using `ctx.run()`. If the workflow retries, the cached result of the `charge-payment` step will be returned instead of re-executing the payment service. ```typescript export const POST = serve(async (ctx) => { // If workflow retries, this returns cached result instead of re-executing const payment = await ctx.run("charge-payment", async () => { return await paymentService.charge(amount); }); }); ``` -------------------------------- ### Workflow Endpoint - Next.js Integration Source: https://context7_llms Example of creating a workflow endpoint within a Next.js App Router project. It demonstrates how to use the `serve` function to handle workflow logic and step caching. ```javascript // 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 }; }); ``` -------------------------------- ### Create Schedule using cURL Source: https://context7_llms Creates a new schedule via cURL. This command-line example demonstrates how to send a POST request to the QueueBear API with necessary details like destination, cron, timezone, and body. Ensure to include the Authorization header. ```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\"}" }' ``` -------------------------------- ### GET /v1/projects/:projectId/workflows/runs/{runId} Source: https://context7_llms Retrieves detailed information about a specific workflow run, including its status, input, output, and the status of each individual step. ```APIDOC ## GET /v1/projects/:projectId/workflows/runs/{runId} ### Description Retrieves detailed information about a specific workflow run, including its status, input, output, and the status of each individual step. ### 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. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **id** (string) - Unique ID of the run. - **workflowId** (string) - ID of the workflow. - **status** (string) - Current status of the run (e.g., 'pending', 'running', 'completed', 'failed'). - **input** (object) - Input data provided to the run. - **output** (object) - Output data from the run. - **createdAt** (string) - Timestamp when the run was created. - **completedAt** (string) - Timestamp when the run was completed. - **steps** (array) - An array of step objects detailing the execution. - **stepName** (string) - Name of the step. - **stepIndex** (integer) - Order of the step. - **stepType** (string) - Type of the step (e.g., 'run', 'sleep', 'call'). - **status** (string) - Status of the step. - **result** (object) - Result of the step execution. - **error** (object) - Error details if the step failed. - **createdAt** (string) - Timestamp when the step started. - **completedAt** (string) - Timestamp when the step 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 } ] } ``` ### Workflow Run Status Values - pending - Queued, not yet started - running - Currently executing - sleeping - Paused in a sleep step - waiting_event - Waiting for external event - completed - Finished successfully - failed - Failed - cancelled - Manually cancelled - timed_out - Exceeded max duration ### Step Types - run - Execute step function - sleep - Pause for duration - call - HTTP request - wait_event - Wait for external event ``` -------------------------------- ### Wait for Service Availability Event Source: https://context7_llms This example shows how to use `ctx.waitForEvent` to pause a workflow until a specific service becomes available, indicated by a "service.available" event. This handles dependencies on other services and includes a configurable timeout. ```typescript const result = await ctx.waitForEvent( "wait-for-service", "service.available", { eventKey: ctx.input.orderId, timeoutSeconds: 4 * 60 * 60 // Wait up to 4 hours } ); ``` -------------------------------- ### cURL: Trigger Workflow Source: https://context7_llms Example cURL command to trigger a workflow in QueueBear. It specifies the workflow ID, the URL for the workflow, input data, and an idempotency key. ```curl curl -X POST "https://queuebear.example.com/v1/projects/proj_xxx/workflows/user-onboarding/trigger" \ -H "Authorization: Bearer qb_live_xxxxx" \ -H "Content-Type: application/json" \ -d '{ "workflowUrl": "https://your-app.com/api/workflows/onboarding", "input": {"userId": "123", "email": "user@example.com"}, "idempotencyKey": "onboarding-user-123" }' ``` -------------------------------- ### Idempotent Webhook Receiver using Node.js and Express Source: https://context7_llms This example shows how to create an idempotent webhook receiver using Node.js and Express. It checks for an existing order in the database before creating a new one to prevent duplicate processing. If the order already exists, it returns a success message. ```javascript app.post("/webhooks/order", async (req, res) => { const { orderId } = req.body; // Check if already processed const existing = await db.orders.findUnique({ where: { id: orderId } }); if (existing) { return res.json({ success: true, message: "Already processed" }); } await db.orders.create({ data: { id: orderId, ... } }); res.json({ success: true }); }); ``` -------------------------------- ### Get Completed Steps for Debugging (Node.js) Source: https://context7_llms Retrieves all completed steps from the context for debugging purposes. It logs the number of completed steps to the console. This function relies on the 'context' object, which is assumed to be available in the scope. ```javascript const steps = await context.getCompletedSteps(); console.log(`Completed ${steps.length} steps`); ``` -------------------------------- ### GET /v1/projects/:projectId/workflows/{workflowId}/runs Source: https://context7_llms Retrieves a list of past and current runs for a specific workflow. You can filter the results by status and paginate through the list. ```APIDOC ## GET /v1/projects/:projectId/workflows/{workflowId}/runs ### Description Retrieves a list of past and current runs for a specific workflow. You can filter the results by status and paginate through the list. ### 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. #### Query Parameters - **status** (string) - Optional - Filter by status (e.g., 'running', 'completed', 'failed'). - **limit** (integer) - Optional - Max results per page (1-100, default: 50). - **offset** (integer) - Optional - Pagination offset (default: 0). #### Request Body None ### Response #### Success Response (200) - **runs** (array) - An array of workflow run objects. - **id** (string) - Unique ID of the run. - **workflowId** (string) - ID of the workflow. - **status** (string) - Current status of the run. - **input** (object) - Input data provided to the run. - **output** (object) - Output data from the run. - **createdAt** (string) - Timestamp when the run was created. - **completedAt** (string) - Timestamp when the run was completed. - **pagination** (object) - Pagination details. - **limit** (integer) - The limit used for the request. - **offset** (integer) - The offset used for the request. - **hasMore** (boolean) - Indicates if there are more results. #### 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 } } ``` ``` -------------------------------- ### QueueBear: Cancel-and-Republish Adaptive Retry Pattern Source: https://context7_llms This Node.js example implements the cancel-and-republish strategy for adaptive retries. It involves publishing a message with a `failureCallbackUrl`, handling the callback to classify failures, and then republishing the message with adjusted delays and retries based on the failure type. ```javascript // 1. Publish with failure callback await qb.messages.publish(destination, payload, { retries: 3, failureCallbackUrl: "https://app.com/api/adaptive-retry", }); // 2. Handle failure callback app.post("/api/adaptive-retry", async (req, res) => { const { messageId, destination, error, attempts } = req.body; const failureType = classifyFailure(extractStatusCode(error), error); // Don't retry permanent failures if (failureType === 'permanent') { return res.json({ action: 'abandoned' }); } // Get original message const message = await qb.messages.get(messageId); // Republish with adaptive delay based on failure type const delay = failureType === 'timeout' ? '2m' : '30s'; const { messageId: newId } = await qb.messages.publish( destination, JSON.parse(message.body), { delay, retries: 2, failureCallbackUrl: "https://app.com/api/adaptive-retry", } ); res.json({ action: 'republished', newMessageId: newId }); }); ``` -------------------------------- ### Long-running Saga with Human Approval and Event Waiting Source: https://context7_llms This example illustrates a long-running saga that requires human approval. It uses `ctx.waitForEvent` to pause the workflow until an "order.approved" event is received, with a timeout for the approval process. ```typescript const approval = await ctx.waitForEvent("wait-approval", "order.approved", { eventKey: orderId, timeoutSeconds: 7 * 24 * 60 * 60, // 7 days }); ``` -------------------------------- ### Get Schedule Source: https://context7_llms Retrieves the details of a specific schedule using its ID. ```APIDOC ## GET /v1/projects/:projectId/schedules/:scheduleId ### Description Retrieves detailed information about a specific schedule, including its configuration, execution history, and any associated metadata. ### 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, plus body, headers, metadata, executionCount, and failureCount. #### 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, "body": "{\"type\": \"daily-report\"}", "headers": { "Content-Type": "application/json" }, "metadata": { "jobName": "daily-report" }, "lastExecutedAt": "2024-01-15T14:00:00Z", "nextExecutionAt": "2024-01-16T14:00:00Z", "executionCount": 42, "failureCount": 2, "createdAt": "2024-01-01T10:00:00Z" } ``` ``` -------------------------------- ### Multi-service Orchestration - Sequential Source: https://context7_llms Demonstrates sequential orchestration of multiple services using `context.run()`. Each step completes before the next one begins, ensuring ordered execution. ```APIDOC ## Sequential Orchestration Example ### Description Orchestrates multiple service calls in a sequential manner. ### Code Example ```javascript export const POST = serve(async (ctx) => { const inventory = await ctx.run("check-inventory", () => inventoryService.check(items)); const payment = await ctx.run("process-payment", () => paymentService.charge(amount)); const shipment = await ctx.run("create-shipment", () => shippingService.ship(items)); return { inventory, payment, shipment }; }); ``` ``` -------------------------------- ### Get DLQ Entry Source: https://context7_llms Retrieves details of a specific entry from the Dead Letter Queue. ```APIDOC ## GET /v1/projects/:projectId/dlq/:entryId ### Description Retrieves the detailed information for a specific entry within the Dead Letter Queue. ### 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) - Returns the full details of the DLQ entry, similar to the list response but for a single entry. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "originalMessageId": "b2c3d4e5-f678-9012-bcde-f12345678901", "destination": "https://api.example.com/webhook", "method": "POST", "failureReason": "Connection timeout", "lastStatusCode": 504, "totalAttempts": 4, "lastAttemptAt": "2024-01-15T10:05:00Z", "createdAt": "2024-01-15T10:00:00Z" } ``` ``` -------------------------------- ### Serve() - Create a Workflow Endpoint Source: https://context7_llms The `serve()` function creates an HTTP handler for your workflow. It receives requests from QueueBear, executes your workflow code, and manages step caching automatically. ```APIDOC ## Serve() - Create a Workflow Endpoint ### Description The `serve()` function creates an HTTP handler for your workflow. It receives requests from QueueBear, executes your workflow code, and manages step caching automatically. ### Basic Usage ```javascript import { serve } from "queuebear"; export const POST = serve(async (context) => { // Your workflow logic here return result; }, options); ``` ### Parameters #### handler - `(context: WorkflowContext) => Promise` - Your workflow function. #### options - `ServeOptions` - Optional configuration. ### Options #### signingSecret - `string` - Secret to verify requests come from QueueBear. ### Framework Integration #### Next.js (App Router) ```javascript // 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 }; }); ``` #### Express ```javascript 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()); }); ``` #### Hono ```javascript 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; }); ``` ### Complete Workflow Example ```javascript // 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) await context.run("send-welcome-email", async () => { // ... logic to send email ... }); return { success: true }; } ); ``` ``` -------------------------------- ### GET /v1/projects/:projectId/messages/{messageId} Source: https://context7_llms Retrieve details of a specific message using its unique ID. ```APIDOC ## GET /v1/projects/:projectId/messages/{messageId} ### Description Retrieves the details of a specific message by its unique identifier. This includes destination, method, body, and headers. ### Method GET ### Endpoint /v1/projects/:projectId/messages/{messageId} ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. - **messageId** (string) - Required - The unique ID of the message to retrieve. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **messageId** (string) - The unique ID of the message. - **destination** (string) - The URL the message was/is to be delivered to. - **method** (string) - The HTTP method used for delivery. - **body** (string) - The payload of the message (JSON string). - **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 /v1/projects/:projectId/dlq/{dlqId} Source: https://context7_llms Retrieves a specific Dead Letter Queue (DLQ) entry by its ID. ```APIDOC ## GET /v1/projects/:projectId/dlq/{dlqId} ### Description Retrieves a specific Dead Letter Queue (DLQ) entry by its ID. ### 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. ### 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 request body of the original message. - **headers** (object) - The request headers of the original message. - **failureReason** (string) - The reason for the message being in the DLQ. - **lastStatusCode** (integer) - The status code of the last attempt. - **totalAttempts** (integer) - The total number of attempts made to process the message. - **lastAttemptAt** (string) - The timestamp of the last 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 { "id": "a1b2c3d4-e5f6-7890-abcd-ef123456789012", "originalMessageId": "f0e9d8c7-b6a5-4321-fedc-ba9876543210", "destination": "/some/endpoint", "method": "POST", "body": { "key": "value" }, "headers": { "Content-Type": "application/json" }, "failureReason": "Processing error", "lastStatusCode": 500, "totalAttempts": 3, "lastAttemptAt": "2023-10-27T10:00:00Z", "recoveredAt": null, "recoveryMessageId": null, "createdAt": "2023-10-27T09:00:00Z" } ``` -------------------------------- ### SAGA Patterns - Implementing Compensation Source: https://context7_llms Illustrates how to implement SAGA patterns using try/catch blocks with `context.run()` for forward and compensating transactions. This ensures data consistency in distributed systems. ```APIDOC ## POST /serve (with SAGA compensation) ### Description Implements SAGA pattern with forward and compensating transactions using `context.run()`. ### Method POST ### Endpoint `/serve` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Assumed to be handled by the `serve` function context) #### Usage Use `ctx.run(stepName, asyncFn)` for both forward and compensating actions. Catch errors in forward transactions and execute compensating actions within the catch block. ``` -------------------------------- ### JavaScript: Trigger and Manage Workflows with QueueBear SDK Source: https://context7_llms Demonstrates how to initialize the QueueBear SDK, trigger a workflow, check its status, and wait for its completion. This requires the 'queuebear' package and valid API credentials. ```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); ``` -------------------------------- ### Initialize QueueBear Client with TypeScript SDK Source: https://context7_llms Initializes the QueueBear client using the TypeScript SDK. Requires an API key and project ID for authentication. The client provides access to modules for messages, schedules, DLQ, and workflows. ```typescript import { QueueBear, serve } from "queuebear"; const qb = new QueueBear({ apiKey: "qb_live_xxx", projectId: "proj_xxx", }); ``` -------------------------------- ### Get Message Details with QueueBear SDK Source: https://context7_llms Retrieves the details of a specific message using its ID via the QueueBear SDK. This includes accessing its status and delivery logs. ```javascript const message = await qb.messages.get(messageId); console.log(message.status); console.log(message.deliveryLogs); ``` -------------------------------- ### cURL: Check Message Status Source: https://context7_llms A simple cURL command to retrieve the status of a specific message using its unique ID. It performs a GET request to the QueueBear messages endpoint. ```curl curl "https://queuebear.example.com/v1/projects/proj_xxx/messages/a1b2c3d4-e5f6-7890-abcd-ef1234567890" \ -H "Authorization: Bearer qb_live_xxxxx" ``` -------------------------------- ### List Schedules Source: https://context7_llms Retrieves a list of all schedules for a given project, with optional pagination parameters. ```APIDOC ## GET /v1/projects/:projectId/schedules ### Description Retrieves a list of schedules associated with a project. Supports pagination to manage large numbers of schedules. ### Method GET ### Endpoint /v1/projects/:projectId/schedules ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project. #### Query Parameters - **limit** (integer) - Optional - Maximum number of 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 number of successful executions. - **failureCount** (integer) - The number of failed executions. - **createdAt** (string) - The creation time in ISO format. - **pagination** (object) - Pagination details. - **limit** (integer) - The limit used for the query. - **offset** (integer) - The offset used for the query. - **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 } } ``` ``` -------------------------------- ### cURL: Publish Message with Delay Source: https://context7_llms Example cURL command to publish a message to QueueBear with a specified delay and number of retries. It uses a POST request to the QueueBear publish endpoint with JSON payload. ```curl 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 }' ``` -------------------------------- ### Workflow Context Methods Source: https://context7_llms Methods available within serve() handlers via the context parameter for advanced workflow control and execution. ```APIDOC ## Workflow Context Methods Available in `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. - **fn** (function) - Required - The function to execute for the step. - **options** (object) - Optional - Configuration options for the step. **Example:** ```javascript const result = await context.run("fetch-user", async () => { return await db.users.findById(userId); }); ``` ### `context.sleep(stepName, seconds)` **Description:** Pauses workflow execution for a specified duration. **Parameters:** - **stepName** (string) - Required - A unique name for the step. - **seconds** (number) - Required - The duration to sleep in seconds. **Example:** ```javascript await context.sleep("wait-1-hour", 3600); ``` ### `context.sleepUntil(stepName, date)` **Description:** Pauses workflow execution until a specific date and time. **Parameters:** - **stepName** (string) - Required - A unique name for the step. - **date** (Date) - Required - The target date and time to resume execution. **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 step. - **config** (object) - Required - Configuration for the HTTP call (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 step. - **eventName** (string) - Required - The name of the event to wait for. - **options** (object) - Optional - Configuration options including `eventKey` and `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 (does not wait for a response). **Parameters:** - **eventName** (string) - Required - The name of the event to notify. - **payload** (object) - Optional - Data to include 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 `fn`. **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:** Retrieves a list of all steps that have been completed in the current workflow run. **Example:** ```javascript const completedSteps = context.getCompletedSteps(); ``` ``` -------------------------------- ### Create Schedule with QueueBear SDK Source: https://context7_llms Creates a new schedule using the QueueBear SDK. It requires destination, cron, timezone, method, body, headers, retries, and metadata. The SDK handles the creation process internally. ```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" }, }); ``` -------------------------------- ### Publish Message using QueueBear REST API (cURL) Source: https://context7_llms Demonstrates publishing a message to QueueBear using a cURL command. This method requires specifying the project ID, API key in the Authorization header, and the message details (destination, body, delay, etc.) in the JSON request body. Useful for testing or environments where the SDK is not available. ```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" } }' ``` -------------------------------- ### Workflow Endpoint - Hono Integration Source: https://context7_llms Demonstrates integrating QueueBear's `serve` function with the Hono web framework. It sets up a POST route to handle workflow requests. ```javascript 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; }); ``` -------------------------------- ### Multi-service Orchestration - Parallel Source: https://context7_llms Shows how to execute multiple service calls in parallel using `context.parallel()`. This is useful for fetching data from different sources concurrently to improve performance. ```APIDOC ## Parallel Orchestration Example ### Description Orchestrates multiple service calls in parallel. ### Code Example ```javascript const [user, orders, recommendations] = await ctx.parallel([ { name: "fetch-user", fn: () => userService.get(userId) }, { name: "fetch-orders", fn: () => orderService.list(userId) }, { name: "fetch-recs", fn: () => recService.get(userId) }, ]); ``` ``` -------------------------------- ### Sequential Multi-Service Orchestration Source: https://context7_llms This snippet illustrates sequential orchestration of multiple services within a workflow. Each service call (`check-inventory`, `process-payment`, `create-shipment`) is executed one after another, with the output of each step being used in subsequent steps. ```typescript export const POST = serve(async (ctx) => { const inventory = await ctx.run("check-inventory", () => inventoryService.check(items)); const payment = await ctx.run("process-payment", () => paymentService.charge(amount)); const shipment = await ctx.run("create-shipment", () => shippingService.ship(items)); return { inventory, payment, shipment }; }); ``` -------------------------------- ### Get DLQ Entry - QueueBear SDK Source: https://context7_llms Retrieves a specific Dead Letter Queue (DLQ) entry using its ID. This function returns an object containing details about the failed message, including its original body, headers, and retry attempts. ```javascript const entry = await qb.dlq.get(dlqId); console.log(entry.body); console.log(entry.totalAttempts); ``` -------------------------------- ### Handling Service Downtime - Workflow Checkpoint/Resume Source: https://context7_llms Explains that workflows automatically checkpoint after each step and resume from the last completed step upon retry. Provides an API to manually retry a failed workflow. ```APIDOC ## `qb.workflows.retry(runId)` ### Description Manually retries a previously failed workflow. ### Parameters - **runId** (string) - Required - The unique identifier of the workflow run to retry. ```