-
-
Notifications
You must be signed in to change notification settings - Fork 612
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
New React to PDF example task (#1300)
* Better code snippet to clarify your framework * New page for react-pdf * Added 3 more examples * New react to PDF example * Alphabeticalise the side menu * Removed github link and tweaked title
- Loading branch information
Showing
6 changed files
with
200 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
--- | ||
title: "Call OpenAI with retrying" | ||
sidebarTitle: "OpenAI with retrying" | ||
description: "This example will show you how to call OpenAI with retrying using Trigger.dev." | ||
--- | ||
|
||
## Overview | ||
|
||
Sometimes OpenAI calls can take a long time to complete, or they can fail. This task will retry if the API call fails completely or if the response is empty. | ||
|
||
## Task code | ||
|
||
```ts trigger/openai.ts | ||
import { task } from "@trigger.dev/sdk/v3"; | ||
import OpenAI from "openai"; | ||
|
||
const openai = new OpenAI({ | ||
apiKey: process.env.OPENAI_API_KEY, | ||
}); | ||
|
||
export const openaiTask = task({ | ||
id: "openai-task", | ||
//specifying retry options overrides the defaults defined in your trigger.config file | ||
retry: { | ||
maxAttempts: 10, | ||
factor: 1.8, | ||
minTimeoutInMs: 500, | ||
maxTimeoutInMs: 30_000, | ||
randomize: false, | ||
}, | ||
run: async (payload: { prompt: string }) => { | ||
//if this fails, it will throw an error and retry | ||
const chatCompletion = await openai.chat.completions.create({ | ||
messages: [{ role: "user", content: payload.prompt }], | ||
model: "gpt-3.5-turbo", | ||
}); | ||
|
||
if (chatCompletion.choices[0]?.message.content === undefined) { | ||
//sometimes OpenAI returns an empty response, let's retry by throwing an error | ||
throw new Error("OpenAI call failed"); | ||
} | ||
|
||
return chatCompletion.choices[0].message.content; | ||
}, | ||
}); | ||
|
||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
--- | ||
title: "Generate a PDF using react-pdf and save it to R2" | ||
sidebarTitle: "React to PDF" | ||
description: "This example will show you how to generate a PDF using Trigger.dev." | ||
--- | ||
|
||
## Overview | ||
|
||
This example demonstrates how to use Trigger.dev to generate a PDF using `react-pdf` and save it to Cloudflare R2. | ||
|
||
## Task code | ||
|
||
```ts trigger/generateResumePDF.ts | ||
import { logger, task } from "@trigger.dev/sdk/v3"; | ||
import { Document, Page, Text, View } from "@react-pdf/renderer"; | ||
import { renderToBuffer } from "@react-pdf/renderer"; | ||
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3"; | ||
|
||
// Initialize S3 client | ||
const s3Client = new S3Client({ | ||
region: "auto", | ||
endpoint: process.env.S3_ENDPOINT, | ||
credentials: { | ||
accessKeyId: process.env.R2_ACCESS_KEY_ID ?? "", | ||
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY ?? "", | ||
}, | ||
}); | ||
|
||
export const generateResumePDF = task({ | ||
id: "generate-resume-pdf", | ||
run: async (payload: { text: string }) => { | ||
logger.log("Generating PDF resume", payload); | ||
|
||
// Render the ResumeDocument component to a PDF buffer | ||
const pdfBuffer = await renderToBuffer( | ||
<Document> | ||
<Page size="A4"> | ||
<View> | ||
<Text>{payload.text}</Text> | ||
</View> | ||
</Page> | ||
</Document> | ||
); | ||
|
||
// Generate a unique filename | ||
const filename = `${payload.text | ||
.replace(/\s+/g, "-") | ||
.toLowerCase()}-${Date.now()}.pdf`; | ||
|
||
// Upload to R2 | ||
const s3Key = `resumes/${filename}`; | ||
const uploadParams = { | ||
Bucket: process.env.S3_BUCKET, | ||
Key: s3Key, | ||
Body: pdfBuffer, | ||
ContentType: "application/pdf", | ||
}; | ||
|
||
logger.log("Uploading to R2 with params", uploadParams); | ||
|
||
// Upload the PDF to R2 and return the URL. | ||
await s3Client.send(new PutObjectCommand(uploadParams)); | ||
const s3Url = `https://${process.env.S3_BUCKET}.s3.amazonaws.com/${s3Key}`; | ||
logger.log("PDF uploaded to R2", { url: s3Url }); | ||
return { pdfUrl: s3Url }; | ||
}, | ||
}); | ||
|
||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
--- | ||
title: "Send a sequence of emails using Resend" | ||
sidebarTitle: "Resend email sequence" | ||
description: "This example will show you how to send a sequence of emails over several days using Resend with Trigger.dev." | ||
--- | ||
|
||
## Overview | ||
|
||
Each email is wrapped in retry.onThrow. This will retry the block of code if an error is thrown. This is useful when you don’t want to retry the whole task, but just a part of it. The entire task will use the default retrying, so can also retry. | ||
|
||
Additionally this task uses wait.for to wait for a certain amount of time before sending the next email. During the waiting time, the task will be paused and will not consume any resources. | ||
|
||
## Task code | ||
|
||
```ts trigger/email-sequence.ts | ||
import { Resend } from "resend"; | ||
|
||
const resend = new Resend(process.env.RESEND_ASP_KEY); | ||
|
||
export const emailSequence = task({ | ||
id: "email-sequence", | ||
run: async (payload: { userId: string; email: string; name: string }) => { | ||
console.log(`Start email sequence for user ${payload.userId}`, payload); | ||
|
||
//send the first email immediately | ||
const firstEmailResult = await retry.onThrow( | ||
async ({ attempt }) => { | ||
const { data, error } = await resend.emails.send({ | ||
from: "[email protected]", | ||
to: payload.email, | ||
subject: "Welcome to Trigger.dev", | ||
html: `<p>Hello ${payload.name},</p><p>Welcome to Trigger.dev</p>`, | ||
}); | ||
|
||
if (error) { | ||
//throwing an error will trigger a retry of this block | ||
throw error; | ||
} | ||
|
||
return data; | ||
}, | ||
{ maxAttempts: 3 } | ||
); | ||
|
||
//then wait 3 days | ||
await wait.for({ days: 3 }); | ||
|
||
//send the second email | ||
const secondEmailResult = await retry.onThrow( | ||
async ({ attempt }) => { | ||
const { data, error } = await resend.emails.send({ | ||
from: "[email protected]", | ||
to: payload.email, | ||
subject: "Some tips for you", | ||
html: `<p>Hello ${payload.name},</p><p>Here are some tips for you…</p>`, | ||
}); | ||
|
||
if (error) { | ||
//throwing an error will trigger a retry of this block | ||
throw error; | ||
} | ||
|
||
return data; | ||
}, | ||
{ maxAttempts: 3 } | ||
); | ||
|
||
//etc... | ||
}, | ||
}); | ||
|
||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters