Skip to content

Instantly share code, notes, and snippets.

@thebiltheory
Created March 1, 2024 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebiltheory/da213dfc5be8f68ae7fffe130a0fc70e to your computer and use it in GitHub Desktop.
Save thebiltheory/da213dfc5be8f68ae7fffe130a0fc70e to your computer and use it in GitHub Desktop.
Process payload medias
import sharp from "sharp";
import { Media } from "./collections/Media";
/**
* @see https://github.com/payloadcms/payload/discussions/1834
*/
export const regenerateMediaSizes = async ({ media, payload }) => {
try {
await Promise.all(
media.docs.map(async (mediaDoc) => {
try {
await fetch(mediaDoc.url)
.then((response) => response.blob())
.then(async (blob) => {
const arrayBuffer = await blob.arrayBuffer();
const buffer = await Buffer.from(arrayBuffer, "binary");
const resizedBuffer = await sharp(buffer)
.resize(Media.upload.reziseOptions)
// Apply the format options
.toFormat(
Media.upload.formatOptions.format,
Media.upload.formatOptions.options
)
.toBuffer();
const file = {
data: resizedBuffer,
mimetype: "image/webp",
// mimetype: blob.type,
name: mediaDoc.filename,
size: resizedBuffer.length,
};
await payload.update({
collection: "media",
id: mediaDoc.id,
data: mediaDoc,
file,
overwriteExistingFiles: true,
contentType: blob.type,
});
console.log(
`Media ${mediaDoc.id} (${mediaDoc.filename}) regenerated successfully`
);
});
} catch (err) {
console.error(
`Media ${mediaDoc.id} (${mediaDoc.filename}) failed to regenerate`
);
console.error(err);
}
})
);
} catch (err) {
console.log("Unable to find documents with payload");
console.error(err);
throw new Error("Update images failed");
}
console.log("Media size regeneration completed!");
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment