Last active
June 2, 2021 10:21
-
-
Save stefanjudis/d4fa2c6da4e2b54a8a43f0b57afc4156 to your computer and use it in GitHub Desktop.
A Node.js script to programmatically update uploads of Contentful assets
This file contains 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
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