Skip to content

Instantly share code, notes, and snippets.

@stefanjudis
Last active June 2, 2021 10:21
Show Gist options
  • Save stefanjudis/d4fa2c6da4e2b54a8a43f0b57afc4156 to your computer and use it in GitHub Desktop.
Save stefanjudis/d4fa2c6da4e2b54a8a43f0b57afc4156 to your computer and use it in GitHub Desktop.
A Node.js script to programmatically update uploads of Contentful assets
const { createReadStream } = require("fs");
const { join } = require("path");
const contentful = require("contentful-management");
const client = contentful.createClient({
accessToken: process.env.CTF_TOKEN,
});
async function main() {
const space = await client.getSpace("[SPACE_ID]");
const environment = await space.getEnvironment("master");
// read the file from your machine somewhere
const uploadStream = createReadStream(join(__dirname, "[FILE_NAME]"));
// create a separate upload to link it to an asset later
const upload = await environment.createUpload({ file: uploadStream });
console.log("Created new upload:", upload);
// fetch the asset you want to update
let asset = await environment.getAsset("[ASSET_ID]");
console.log("Fetched asset:", asset);
// use `uploadFrom` field to connect the new upload with the asset
asset.fields.file["en-US"] = {
contentType: "image/jpg",
fileName: "cat.jpg",
uploadFrom: {
sys: {
type: "Link",
linkType: "Upload",
id: upload.sys.id,
},
},
};
// update the asset to include the field changes
console.log("Updating asset");
asset = await asset.update();
console.log("Processing asset");
// process the new upload
asset = await asset.processForAllLocales();
// publish the asset with the new upload
console.log("Publishing asset");
await asset.publish();
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment