Skip to content

Instantly share code, notes, and snippets.

@stefanjudis
Last active June 2, 2021 10:21
Show Gist options
  • Select an option

  • Save stefanjudis/d4fa2c6da4e2b54a8a43f0b57afc4156 to your computer and use it in GitHub Desktop.

Select an option

Save stefanjudis/d4fa2c6da4e2b54a8a43f0b57afc4156 to your computer and use it in GitHub Desktop.

Revisions

  1. stefanjudis revised this gist Jun 2, 2021. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion asset-update.js
    Original file line number Diff line number Diff line change
    @@ -10,7 +10,7 @@ async function main() {
    const space = await client.getSpace("[SPACE_ID]");
    const environment = await space.getEnvironment("master");

    // read the file from you machine somewhere
    // 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 });
  2. stefanjudis created this gist Jun 2, 2021.
    47 changes: 47 additions & 0 deletions asset-update.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    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 you 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();