Search code examples
contentfulcontentful-management

How to tell the webhook the 'unpublish()' order comes from the API, not the Contentful console?


I use this trick (thanks @Robban) to publish a Contentful entry through the API, without triggering the webhook.

However, I could not figure out how to UNpublish an entry through the API without triggering the webhook.

According to the Contentful documentation, to unpublish an entry through the API, it goes like this:

client.getSpace('<space_id>')
  .then((space) => space.getEntry('<entry_id>'))
  .then((entry) => entry.unpublish())

As <entry_id> is the only payload, how could I indicate to the webhook it should not proceed as usual, as it was an API call?


Solution

  • There is unfortunately, again, no difference between a call from the API directly or from the web app. The web app does exactly this call under the hood.

    Further more, in the case of an unpublish the only thing your webhook would recieve is a deletion object which does not contain any fields. This means that the trick shown in the previous answer does not apply here.

    The only way I can think of solving this would be to make another call to some data store (could be Contentful) and put the entry id and perhaps also some timestamp in there. Your webhook could then upon recieving an unpublish event query this datastore and see if processing should continue or if it seems the unpublish was made through the web app.

    Basically something like this:

    client.getSpace('<space_id>')
    .then((space) => space.getEntry('<entry_id>'))
    .then((entry) => {
    
             otherService.SetUnpublishedThroughManualAPICall(entry.sys.id);
             entry.unpublish();
    
          })
    

    Then in your webhook with some pseudo code:

    function HandleUnpublish(object entry) {
    
        if(OtherService.CheckIfManualUnpublish(entry.sys.id)){
             //Do some processing...
        }
    }
    

    You could opt to use a field in Contentful as your store for this. In that case you would just before unpublishing set this field. Something like this:

    client.getSpace('<space_id>')
    .then((space) => space.getEntry('<entry_id>'))
    .then((entry) => { 
         entry.fields['en-US'].unpublishedTroughApi = true;
         entry.update();
     })
    .then((entry) => entry.unpublish())
    

    Then in your webhook you would have to fetch the entry again via the management API and inspect the field. Keep in mind that this would result in a number of extra API calls to Contentful.