Do more with Dgraph Lambda - Dgraph Blog

Do more with Dgraph Lambda

Dgrapgh Lambda in Slash GraphQL is a serverless framework that lets you run Javascript or Typescript function in response to GraphQL queries or mutations. This helps in simplifying development - now you can embed business logic or trigger events on GraphQL queries/mutations.

What can I do with Dgraph Lambda?

These are the broad classification of use cases that you can solve with Dgraph Lambda out of the box:

  1. Notify users of an event (a mutation)
  2. Trigger jobs or your custom data pipelines
  3. Perform data derivations or transformations
  4. Perform data sanitization

Notify users of an event

Lambda can be used to notify your app users on events. GraphQL operations can be modelled as events. For example, if you are building a user subscription form, you can trigger an email to confirm the subscription when people sign up by creating an event for executing a mutation (creating user object). This can be easily done with lambda by triggering a simple HTTP request to your email delivery service like Twilio Sendgrid. (Checkout sample code).

Steps:

  1. A GraphQL mutation executed.
  2. Lambda act as a proxy to the GraphQL mutation. It intercepts the mutation and invokes a function.
  3. The function triggers an HTTP request to SendGrid API (in this example) to deliver an email to the subscriber with the help of incoming data.
  4. The input data in the incoming mutation can be written to the database.

Trigger jobs or your custom data pipelines

You can use lambda to automate time-consuming jobs, data pipelines or machine learning models that can be asynchronously executed. For example if you have a text classifier machine learning model service, you can use lambda to call this service. This will trigger the classification service. On completion of model service execution, the result can be written to the database based on the incoming payload.

Steps:

  1. A GraphQL mutation is executed.
  2. Lambda act as a proxy to the GraphQL mutation. It intercepts the mutation and executes a function.
  3. The function triggers signals your data pipeline (example - via HTTP). The data pipeline can execute its workflow based on the payload asynchronously and write back results on completion.
  4. The data in the incoming mutation can be written to the database.

Perform data derivations or transformations

You can perform simple data derrivations & light weight transformation on lambda. For example - aggregation of fields, string concatenations, rounding off numbers, etc.

Steps:

  1. A GraphQL mutation is executed.
  2. Lambda intercepts the query, fetched data from the database
  3. Lambda returns the result after performing a transformation - for example computing full name without actually storing it.

Perform data sanitization

You can perform data sanitzation using lambda. For example - handling missing data, trimming text, filter unwanted values, etc.

Steps:

  1. A GraphQL mutation is executed.
  2. Lambda intercepts the mutation.
  3. Lambda writes data into the database after sanitization (Example - removing trailing spaces from the text)

Example with code

A backend that allows user to store subscriber data (name & email) and sends a welcome email using SendGrid API to the email being stored.

Schema

type Subscriber  {
	name: String!
	email: String!
}
input CreateSubscriberInput {
	name: String!
	email: String!
}
type Mutation {
  createSubscriber(subscriber: CreateSubscriberInput): Subscriber @lambda
}

Lambda

self.addGraphQLResolvers({
 "Mutation.createSubscriber": createSubscriber,
});
async function createSubscriber({ args, graphql }) {
 const { subscriber } = args;
 const results = await graphql(
   `
     mutation($name: String!, $email: String!) {
       addSubscriber(input: { name: $name, email: $email }) {
         subscriber {
           email
           name
         }
       }
     }
   `,
   { ...subscriber }
 );
 const { email, name } = subscriber;
 sendMail(email, name);
 return results.data.addSubscriber.subscriber[0];
}
function sendMail(email, name) {
 var myHeaders = new Headers();
 myHeaders.append(
   "Authorization",
   "Bearer {{YOUR_TOKEN_FROM_SENDGRID}}"
 );
 myHeaders.append("Content-Type", "application/json");
 var raw = JSON.stringify({
   personalizations: [
     {
       to: [
         {
           email: email,
           name: name,
         },
       ],
       subject: "Welcome",
     },
   ],
   content: [
     {
       type: "text/plain",
       value: "You are added to the subscription!",
     },
   ],
   from: {
     email: "thiyaga@dgraph.io",
     name: "Thiyagaraj T",
   },
 });
 var requestOptions = {
   method: "POST",
   headers: myHeaders,
   body: raw,
   redirect: "follow",
 };
 fetch("https://api.sendgrid.com/v3/mail/send", requestOptions)
   .then((response) => response.text())
   .then((result) => console.debug(result))
   .catch((error) => console.error("error", error));
}

The example creates a backend that stores subscribers’ data - The graphql schema exposes a custom mutation createSubscriber that is annotated with @lambda directive. The lambda script registers a javascript function against createSubscriber mutation. This function will be invokend whenever a createSubscriber mutation is executed.

Summary

Dgraph Lambda allows you to simplify development and build a reactive backend. You can trigger webhooks to connect with your other microservices, queues, third party services and do more than database operations. Try Dgraph Lambda on Slash GraphQL now!

Useful resources to get started

https://dgraph.io/blog/post/lambda-slash-graphql/

https://dgraph.io/docs/graphql/lambda/overview/

https://dgraph.io/docs/graphql/lambda/mutation/

https://github.com/dgraph-io/dgraph-lambda


This is a companion discussion topic for the original entry at https://dgraph.io/blog/post/dgraph-lambda/