Created
March 1, 2024 04:25
-
-
Save thebiltheory/da213dfc5be8f68ae7fffe130a0fc70e to your computer and use it in GitHub Desktop.
Process payload medias
This file contains hidden or 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
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