Over 10 years we help companies reach their financial and branding goals. Engitech is a values-driven technology agency dedicated.

Gallery

Contacts

411 University St, Seattle, USA

engitech@oceanthemes.net

+1 -800-456-478-23

Nodejs REST APIs with Temporal

Temporal makes sure that code executes durably, reliably, and scalably while excluding unnecessary complication for developers. Before going to the details of Node js REST APIs with Temporal, let’s have a brief overview of

  1. What is temporal.io and how does it work?
  2. Why should we use temporal?
  3. How we can install it and how to use it in a nodejs application.

What is Temporal:

Temporal is known as the developer-first open-source platform which makes sure the execution of applications and services while using the workflows. Temporal.io is a workflow engine that is able to coordinate microservices and can be developed by writing code and we can use its parts over and over again with a modular architecture.

Why Temporal?

Workflow execution in Temporal is a Reentrant process that is resumable, reactive & recoverable. 

  • Resumable: Ability of any process to continue the execution when execution was suspended earlier on an available.
  • Reactive: Ability of any process to react to external events.·        
  • Recoverable: Ability of a process to continue the execution after the execution was suspended on a failure.·        
  • Reliable         
  • Durable·        
  • Scalable

Core concepts:

  • Workflows
  • Workers
  • Activity
  • Retry Policies

We will discuss more of these concepts below, in detail.

Temporal SDKs:

Temporal provides different SDKs to run with our existing applications

Listed below:

  1. GO SDK
  2. Java SDK
  3. Typescript SDK
  4. Python SDK

Temporal fully supports Nodejs applications and since nodejs is a javascript library, we can use Typescript SDK with it. 

How can we install Temporal?

To run temporal on windows or on mac we need:

Prerequisites:

  • Nodejs 14+
  • Docker
  • Docker-compose

We need to run a Temporal server, this is how you can do it. 

git clone https://github.com/temporalio/docker-compose.git temporal
cd temporal
docker-compose up

If you are on windows you need: 

  • Docker-desktop
  • Wsl ~ a subsystem for Linux

Before starting with our project as promised here are things you need to understand:

Workflow:

Workflows are known as async functions which can rewrite Activities and access APIs of special workflows, that are subject to the deterministic limitation. There are two parts of each Workflow:

  • Function name is also knowns as Workflow Type
  • Function implementation code is known as Workflow Definition.

Worker:

A process that connects the Temporal Server and polls Task Queues to the tasks that are sent from the clients and then executes the Activities and Workflows in response is known as a Worker. 

Activity:

The only way, the interaction with external resources is made in the Temporal is through Activities like file system access and making an HTTP request

Unlike Workflows, Activities are executed in the standard environment of Node.js. A code should be in an activity in order to talk to the outside world. It should not be in a Workflow.

LET’S GET STARTED:

Now we know what Temporal is and its concepts, so now we are good to go and use it in our project. I am assuming that you already have a piece of good knowledge of NodeJS and Rest APIs.

Firstly we need to run a worker in order to use our workflows and activities.

So let’s create an endpoint to create and run Worker.

app.post(“/create-and-run-worker”, async (req, res) => {
  console.log(“Create & RUN worker API called”);

  try {
    const worker = await Worker.create({
      workflowsPath: require.resolve(“./workflow”),
      taskQueue: req.body.uuid,
    });
    console.log(“create Worker”);
    worker.run();
    console.log(“create & run worker API response”);
    res.end();
  } catch (err) {
    console.log(“Create worker error: “, err);
  }
});

We created an endpoint /create-and-run-worker after that we created an instance of Worker which resolves the path where our workflow resides, in my case its ./workflow and it takes a queue to run our workflows on. Finally, we run the worker using worker.run() 

Now our worker is running so let’s see how we can start a workflow

Creating another API for the single workflow to start

app.post(“/run-workflow”, async (req, res) => {
  console.log(“RUN workflow API called”);
  const {body:{username}} = req;
  const client = getClient();
 
  try {
    await client.start(GreetUserWorkflow, {
      args: [{ username }],
      taskQueue: ‘same queue used to create the worker’,
 workflowId: ‘an ID to identify the workflow’,
     });
    const result = await client.result();
    console.log(“result: “, result) // greeting message //
    res.send(result);
  } catch (err) {
    console.log(“Create worker error: “, err);
  }
});

As In our api we have set up  our client which is starting GreetUserWorkflow, so let’s create This workflow.

Workflow Code:

Workflow is a simple function that calls the activity that does all the work, and returns a response back to the user.

Explanation: 

GreetUserWorkflow is called workflow type and all the code inside workflow is called workflow definition 

export async function GreetUserWorkflow(username: string) {
  const greeting = await greetActivity(username);
  return greeting;
}

Activity Code:

All the API calls and outside world logic will be written in this function.

export async function greetActivity(username: string) {
  return  `Hello ${username}, Welcome to Temporal`;
};

That’s how you can create REST APIs to run temporal and use workflows and activities.

Hope you liked this article

Give a thumbs up, and share it with more people

Stay tuned for more exciting and interesting blog posts! 

Recent Posts

Subscribe to get notifications for Latest Blogs