Action

Drafts››Cosmic

Posted by Karl Koch, Last update almost 4 years ago

Post to CosmicJS

My site runs on CosmicJS for posting blog content, it’s a simple headless CMS that is low friction but powerful.

There’s not many resources out there that connect to it so I wanted to write an action to post my blogs directly from Drafts into CosmicJS without duplication of effort. This action preserves the body markdown as HTML so it’s accepted in to Cosmic’s content block as expected. No markup necessary.

By default it posts as a “draft”, but I’d recommend changing this to “published” once you’re comfortable with how it works as it saves a step later.

Steps

  • script

    let title = draft.displayTitle;
    let content = draft.processTemplate("%%[[body]]%%");
    let date = draft.processTemplate("[[modified]]");
    let snippet = draft.bodyPreview(140);
    
    var http = HTTP.create(); // create HTTP object
    var response = http.request({
      "url": "https://api.cosmicjs.com/v1/your_cosmic_slug/add-object", // Add your Cosmic slug, you can find it in your user settings
      "method": "POST",
      "data": {
      "title": title, // default Cosmic data point for the object title
      "content": content, // default Cosmic data point for the body content
      "type_slug": "your_object_slug", // find this in your Object's settings
      "metafields": [ // If these fields don't exist, Cosmic will create the metafields and fill the data for you... awesome
        {
          "key": "value", // e.g. published-date
          "title": "value", // e.g. Published on
          "type": "date",
          "value": date,
        },
        {
          "key": "value", // e.g. snippet
          "title": "value", // e.g. Content snippet
          "type": "text",
          "value": snippet,
        }
      ],
      "status": "draft", // e.g. "draft" / "published"
      "write_key": "your_cosmic_write_key"
    	},
    });

Options

  • After Success Default
    Notification Info
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.