Over a million developers have joined DZone.

How to Use a Precommit Hook in Riak

DZone's Guide to

How to Use a Precommit Hook in Riak

· Database Zone ·
Free Resource

Running out of memory? Learn how Redis Enterprise enables large dataset analysis with the highest throughput and lowest latency while reducing costs over 75%! 

Book "Seven Databases in Seven Weeks" has an example of how to use a precommit hook in Riak. However, it did not work for me (Riak 1.1.4). The issue is that I was getting the following message for every single commit:

PUT aborted by pre-commit hook

After enabling debug logging in the app.config (*), I realized that it was failing with the following error: 

Problem invoking pre-commit hook: [{<<"lineno">>,1},{<<"message">>,<<"ReferenceError: good_scores is not defined">>},{<<"source">>,<<"unknown">>}]

The problem is that the command to set the precommit hook MUST specify the language, otherwise it doesn't work properly. In order to get the book's example fixed then, do the following: 

curl -i -X PUT http://localhost:8091/riak/animals -H "content-type: application/json" -d '{"props":{"precommit":[{"name":"good_score","language":"javascript"}]}}' 

Once enabled, I was getting the proper error messages. Most importantly, valid data was being accepted and committed by Riak.

You may be wondering how the Javascript looks like. Since I can't copy the book's example due to copyright, this is an example of function that works the same: 

// Makes sure the object has JSON contents
function precommitMustBeJSON(object){
  try {
    return object;
  } catch(e) {
    return {"fail":"Object is not JSON"};

Unfortunately Riak does not have a good tutorial or example on that and it was hard to find the reason for the error. Maybe it'll get better as it matures.

One final thing: don't forget that you need to put your function in a .js file in a directory configured in your app.config. For instance, my file is called "my_validators.js" and it's located in the directory I configured in app.config: 

{js_source_dir, "/home/rdcastro/riak/js_source"}, 

(*) To enable debug logging, make sure your "lager" section has the following settings: 

            {handlers, [
                {lager_console_backend, debug},
                {lager_file_backend, [
                    {"./log/error.log", error, 10485760, "$D0", 5},
                    {"./log/console.log", debug, 10485760, "$D0", 5}




Running out of memory? Never run out of memory with Redis Enterprise databaseStart your free trial today.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}