Skip to content

Instantly share code, notes, and snippets.

@dugjason
Created September 25, 2024 18:09
Show Gist options
  • Save dugjason/8081e69e61b8de804f6aa4d0b950af43 to your computer and use it in GitHub Desktop.
Save dugjason/8081e69e61b8de804f6aa4d0b950af43 to your computer and use it in GitHub Desktop.
React Server Action to create a draft message in Front.com

Based on Next.js server actions, the sendToFrontAction() can be called from client-side components.

It passed a couple of data items to the importFrontMessage() method which reads a file from the local system, and adds it to a draft message.

The message is submitted to the Front Create Draft Message endpoint.

This is an example of that the imported draft might look like given the code provided below:

Screenshot 2024-09-25 at 11 06 41 AM
"use server"
import * as fs from "node:fs"
const FRONT_API_TOKEN = process.env.FRONT_API_TOKEN
export async function sendToFrontAction() {
await importFrontMessage("./Free_Test_Data_2MB_MP3.mp3", "tea_123", "cha_456", [
"[email protected]",
"[email protected]",
])
}
async function importFrontMessage(
filePath: string,
authorId: string,
channelId: string,
recipients: string[],
) {
const formData = new FormData()
formData.append("subject", "Message subject")
formData.append("author_id", authorId)
formData.append("body", "<p>Message body with attachment</p>")
for (const recipient of recipients) {
formData.append("to[]", recipient)
}
// Read the file from the local file system
const fileBuffer = await fs.promises.readFile(filePath)
const fileName = filePath.split("/").pop() || "attachment"
// Append the file to the formData
formData.append("attachments[]", new File([fileBuffer], fileName))
const res = await fetch(`https://api2.frontapp.com/channels/${channelId}/drafts`, {
method: "POST",
body: formData,
headers: {
Accept: "application/json",
Authorization: `Bearer ${FRONT_API_TOKEN}`,
},
})
const data = (await res.json()) as unknown
const messageId = ((data as Record<string, unknown>).id as string) ?? ""
return res.status === 200
? { status: "success", message: `Draft created in Front - ${messageId}` }
: { status: "error", message: res.statusText }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment