This is the forth article in a series on how to use GitHub pages (the service that hosts this blog) and Cloudant on the BlueMix PaaS to create an automatically updating news section for a blog. This post will describe how to configure your Openwhisk chain to make sure news items on your blog are only posted once.
The last article of this series explained how to configure Openwhisk to let us update news articles from the command line. The problem with the simple approach outlined in that post is that the same news item could show up multiple times in the news page.
Look what happens when we call the same Openwhisk action twice with the same values.
Both requests return OK and duplicate entries exist on the news page.
Steps to ensure unique articles
Create a Cloudant index on the link field
Filter news articles with links that already exist in Cloudant
Insert filtered news articles
Another Cloudant index
Creating the initial Cloudant index was described in detail in this post. To create another index open up the Cloudant portal, select Databases from the left navigation section and then select your blog news database. Select the plus sign next to Design Documents then select query indexes.
In the next screen you can create your index. Unlike the previous index, this time we want to index the link of the news articles so we can make sure all news artciles are unique. From the supplied default index example in cloudant replace ‘foo’ with ‘link’ and click create index.
With the index created, Cloudant can now be quickly queried to see if a link already exists.
Filter news articles
Create a file called insert_article.js
The content of the insert_article action in its entirety
Action parameters are passed in with the params object. This action uses title, link, excerpt and timestamp.
Use an asynchronous whisk action to query Cloudant for any documents containing the link passed in as a parameter.
If the results set contains 1 or more documents, end the Openwhisk chain with a call to whisk.done. Otherwise invoke another asynchronous Cloudant whisk action to insert the article.
Execute a whisk.done call after adding the article to Cloudant.
Create and upload the action to Openwhisk
Executing Openwhisk action
Note how the initial run has a result of “Article added to Cloudant” and the second invocation returns a result of “Link already present”.
Looking at the resulting news page, only a single instance of this article has been added to the database.
Now we can add entries to our Cloudant database from the command line without worrying about accidentally duplicating articles.