A simple procedure caller

A simple procedure caller

Sometimes you just need something simple. Something that’s light-weight though capable, and does what you want – nothing more. That’s what I did with procedure-caller, a simple Node.JS module for calling, you guessed it, procedures. To be clear: in this context, a ‘procedure’ is nothing more than a function that can be called repeatedly.

Installing it using npm is child’s play:

npm i @art-of-coding/procedure-caller --save

Now that it’s installed we’ll dive right into an example:

const ProcedureCaller = require('@art-of-coding/procedure-caller')

// Create a new instance
const pc = new ProcedureCaller()

// Define a procedure named 'add', which adds two numbers
pc.define('add', function (a, b) {
  if (isNaN(a) || isNaN(b)) {
    throw new TypeError('arguments must be numbers')
  }

  return a + b
}

// Now call the procedure
const result = pc.call('add', 5, 6)

// Display the result
console.log(`5 + 6 = ${result}`)

As you can see, it’s easy to call a procedure and get the result. But what if we’re using asynchronous methods, like Promises or async/await? That’s covered too!

const ProcedureCaller = require('@art-of-coding/procedure-caller')
// We're using gh-got to talk to the GitHub API
const ghGot = require('gh-got')

const pc = new ProcedureCaller()

// Define an async procedure
pc.define('repo', async function (user, name) {
  const response = await ghGot(`repos/${user}/${name}`)
  return response.body
}

// Call the async procedure
pc.call('repo', 'Art-of-Coding', 'procedure-caller').then(result => {
  console.log(`Repo description: ${repo.description}`)
})

Like I said in the opening of this post, my goal was to make something that was exceedingly simple to use. I believe I have done so.

You can view the module on npm and GitHub.


Leave a Reply

Your email address will not be published. Required fields are marked *