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 Oystehr 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 Oystehr. To do this, we'll need to create a Zambda in Oystehr 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.
Create a Zambda with the v3 SDK:
import Oystehr from '@oystehr/sdk';
const oystehr = new Oystehr({
accessToken: "<your_access_token>",
});
const zambda = await oystehr.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 oystehr.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 v3 SDK:
import Oystehr from '@oystehr/sdk';
const oystehr = new Oystehr({
accessToken: "<your_access_token>",
});
const zambda = await oystehr.zambda.execute(
{
id: 'your_zambda_id',
name: 'Oystehr 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 Oystehr, 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:
import Oystehr from '@oystehr/sdk';
const oystehr = new Oystehr({
projectId: process.env.ZAPEHR_PROJECT_ID,
accessToken: "<your_access_token>",
});
const zambda = await oystehr.zambda.execute({
id: 'hello-world',
name: 'Oystehr 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.