Skip to content

Commit

Permalink
New React to PDF example task (#1300)
Browse files Browse the repository at this point in the history
* 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
samejr authored Sep 13, 2024
1 parent 9a7ad92 commit c1690bd
Show file tree
Hide file tree
Showing 6 changed files with 200 additions and 9 deletions.
8 changes: 2 additions & 6 deletions docs/examples/generate-image-with-dall-e3.mdx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: "Generate an image using DALL·E 3"
sidebarTitle: "Generate image using DALL·E"
sidebarTitle: "DALL·E image generation"
description: "This example will show you how to generate an image using DALL·E 3 and text using GPT-4o with Trigger.dev."
---

Expand Down Expand Up @@ -64,8 +64,4 @@ function generateTextPrompt(theme: string, description: string): any {
function generateImagePrompt(theme: string, description: string): any {
return `Theme: ${theme}\n\nDescription: ${description}`;
}
```

## GitHub repo

View this example task [on GitHub](https://github.com/triggerdotdev/v3-test-projects/blob/main/website-examples/trigger/generateContent.ts).
```
47 changes: 47 additions & 0 deletions docs/examples/open-ai-with-retrying.mdx
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;
},
});

```
69 changes: 69 additions & 0 deletions docs/examples/react-pdf.mdx
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 };
},
});

```
72 changes: 72 additions & 0 deletions docs/examples/resend-email-sequence.mdx
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...
},
});

```
7 changes: 6 additions & 1 deletion docs/mint.json
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,12 @@
},
{
"group": "Examples",
"pages": ["examples/generate-image-with-dall-e3"]
"pages": [
"examples/generate-image-with-dall-e3",
"examples/open-ai-with-retrying",
"examples/react-pdf",
"examples/resend-email-sequence"
]
}
],
"footerSocials": {
Expand Down
6 changes: 4 additions & 2 deletions docs/snippets/cli-commands-develop.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,15 @@ Install the concurrently package as a dev dependency:
concurrently --raw --kill-others npm:dev:remix npm:dev:trigger
```

Then add something like this in your package.json scripts. This assumes you're running Next.js so swap that bit out if you're not:
Then add something like this in your package.json scripts:

```json
"scripts": {
"dev": "concurrently --raw --kill-others npm:dev:*",
"dev:next": "next dev",
"dev:trigger": "npx trigger.dev@beta dev",
// Add your framework-specific dev script here, for example:
// "dev:next": "next dev",
// "dev:remix": "remix dev",
//...
}
```

0 comments on commit c1690bd

Please sign in to comment.