Safe retries
Use upload_token so a retried or duplicated request never posts the same meme twice.
Networks fail in the worst place: after the server created your meme but before
you got the response. Retrying blindly would post it twice. upload_token
prevents that.
How it works
Generate a unique token per meme (a UUID is perfect) and send it with the upload. Keep the same token for every retry of that meme.
-F "upload_token=7b0e1f3a-2c4d-4e5f-8a9b-0c1d2e3f4a5b"- Allowed: 8 to 64 letters, digits and dashes.
- The first request with a token creates the meme.
- Any later request with the same token creates nothing and tells you so:
{
"success": true,
"duplicate_ignored": true,
"content_id": 18301,
"slug_url": "me-explaining-my-code-to-the-rubber-duck-programming",
"message_code": "content_upload_success"
}The meme from the first request. You are done.
{
"success": true,
"duplicate_in_progress": true,
"message_code": "content_upload_success"
}The first request is still being processed. Nothing new was created. Wait a few seconds and retry with the same token to get its IDs.
A retry loop
import { randomUUID } from "node:crypto";
import { openAsBlob } from "node:fs";
const token = randomUUID(); // one token for this meme, reused on every attempt
for (let attempt = 1; attempt <= 5; attempt++) {
try {
const form = new FormData();
form.append("file", await openAsBlob("meme.mp4"), "meme.mp4");
form.append("upload_token", token);
const response = await fetch(
"https://uploads.backend.trollflix.com/api/php/developer/upload_video",
{
method: "POST",
headers: { Authorization: `Bearer ${process.env.TROLLFLIX_API_KEY}` },
body: form,
},
);
const result = await response.json();
if (result.success === true && !result.duplicate_in_progress) {
console.log("Uploaded", result.content_id);
break;
}
if (result.success !== true) {
// A validation error will fail the same way again: stop retrying.
console.error("Rejected", result.error_message_code);
break;
}
} catch (error) {
console.warn(`Attempt ${attempt} failed`, error);
}
await new Promise((resolve) => setTimeout(resolve, attempt * 5000));
}Use a new token for every different meme. Reusing a token for a different video returns the first meme and silently skips the new one.