Writing Zambdas

Writing Zambdas

In this guide we will write, deploy, and execute a Zambda. This guide is intended for developers who are already familiar with Zambda concepts and are looking for a practical guide on the fundamentals of working with Zambdas. If you are instead looking for a production ready implementation, we recommend getting started with Ottehr (opens in a new tab).

Write a Zambda Function

Let's create a Zambda that returns a greeting.

First we'll create a JavaScript file to house the code that will be executed when we make a request to our Zambda. Create a file called index.js with this command:

echo 'const formatJSONResponse = (response) => {
  return {
    statusCode: 200,
    body: JSON.stringify(response),
  };
};
 
exports.index = async (event) => {
  const body = JSON.parse(event.body);
  return formatJSONResponse({
    message: `Hello ${body.name}, welcome to the exciting ZapEHR world!`,
  });
};
' > index.js

Deploy your Zambda

We'll prepare our JavaScript file for upload by zipping it:

zip hello-world.zip index.js

Now we'll upload our Zambda to ZapEHR. To do this, we'll need to create a Zambda in ZapEHR and then upload our zipped file to it. Zambda names are unique per-project, and cannot contain spaces or special characters. We'll use hello-world for this example.

Upload a Zambda with the SDK:

  const zambda = await zapehr.project.zambda.create(
    {
      name: 'hello-world',
      triggerMethod: 'http_auth', // you'll change this based on the type of zambda
    }
  );
  const zambdaFile = fs.readFileSync('hello-world.zip');
  await zapehr.project.zambda.uploadFile(
    zambda.id,
    file: new Blob([zambdaFile]),
  );

Execute your Zambda

To execute your Zambda, execute the following command with your_zambda_id replaced with the ID of the Zambda you created:

Execute a Zambda with the SDK:

  const zambda = await zapehr.project.zambda.execute(
    {
      id: 'your_zambda_id',
      name: 'ZapEHR User',
      // you can submit additional data to your Zambda here
    }
  );

Interacting with Zambdas by Name

You can also interact with specific Zambdas by name instead of ID. This is useful for deploying the same frontend code to multiple environments. For example, let's say you have three Projects in ZapEHR, My Project — development, My Project — staging, and My Project — production. You can give your zambdas the same name in each project and only change the project ID in your code. Using the SDK, it would look like this:

zapehr.init({
  ZAPEHR_PROJECT_ID: process.env.ZAPEHR_PROJECT_ID,
  ZAPEHR_ACCESS_TOKEN: process.env.ZAPEHR_ACCESS_TOKEN,
});
 
const zambda = await zapehr.project.zambda.execute(
  {
    id: 'hello-world',
    name: 'ZapEHR User',
  }
);

This saves you from having to hard-code the Zambda ID in your frontend code, or having to query the API for the Zambda ID each time you want to execute it.