Wednesday, September 1, 2021

Run a GraphQL endpoint for pennies a month with Apollo Server and Azure Functions

Apollo ServerApollo Server

When we build healthcare apps like FHIR BlazeNurseHack4Health's TeamBuilder or internal apps we will always move faster if we're running against a GraphQL middleware.  It doesn't matter if you're building frontend, backend, or accessing PII, a GraphQL middleware will help you move faster.   We've already done a series of videos and posts on how to get up and running with dotnet based GraphQL.  But what if you want to get running RIGHT NOW and you want to do it using JavaScript?

 

Apollo Server is a node.js based GraphQL server.   Read more about Apollo. 

Why deploy in a Function?
Functions are cheap- pay only for execution time.  
Functions minimize boiler plate.  In the sample below you'll see we have 4 files with less than a hundred total lines of code.

Functions scale from 1 invocation a year to 1000s a second with no change on your part.

 

Let's get started. Or skip ahead to the code sample.

 

Setup a New JavaScript Function App

Follow this tutorial to create a new JavaScript function.

Create an anonymous HTTP Triggered function (lets call it graph).

Test by hitting F5.

 

Setup Apollo

Follow these directions to setup Apollo or follow my steps below that walk you through the steps.

Add Required Dependencies

   Run the npm install command with the following packages.

 

npm install apollo-server-azure-functions graphql azure-function-log-intercept

 

   The documentation does not include the azure-functions-log-intercept package, but it will greatly help you.  This package will dump Apollo logs to the console.  If you don't include this package Apollo logs will not be persisted in Azure.

 

Copy the boiler plate

Edit index.js to look like this:

 

const { gql, ApolloServer } = require("apollo-server-azure-functions");

// Construct a schema, using GraphQL schema language
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// A map of functions which return data for the schema.
const resolvers = {
  Query: {
    hello: () => "world"
  }
};

const server = new ApolloServer(
      { typeDefs,
         resolvers,
         introspection: (process.env.NODE_ENV !== 'production'),
         playground: (process.env.NODE_ENV !== 'production'), 
       });

exports.graphqlHandler = server.createHandler({
    cors: {
      origin: '*',
     allowedHeaders:['Content-Type', 'Authorization']
   },
  });

 

 

Edit functions.json to look like this:

 

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "route": "graph",
      "methods": [
        "get",
        "post",
        "options"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ]
}

 

 

Run locally

In Visual Studio Code you should now be able to hit F5, or you can run the following command to start the server:

 

func start

 

When your app starts you'll see a line similar to this:

Running Functions (shows URL of running function)Running Functions (shows URL of running function)

 

If you go to your browser you'll see Apollo's PlayGround IDE up and running.

Want to know how to use the PlayGround?  I'll cover it in a later tutorial.  In the meantime the Apollo tutorial has a great section on how to use the Playground IDE.

 

 

Calculate Costs

There's a lot to cover on what we could do with GraphQL.  But for now let's move on to calculate costs of running Apollo.    Open up the Azure Cost Calculator.

Add a single Azure function. 

Location: Your Choice (I used West US)

Type: Consumption.

Execution time: for each Apollo call will be less than 10ms, but let's keep execution time at 100ms (default).  

Executions: let's say you have 1 execution every second of every minute of every hour of every day for a 31 day month.  (1x60x60x24x31)=2,678,400 executions.

 

Total cost will then be updated, and depending on many factors will be less than $1

Less than $1 to run a world class GraphQL endpoint!!  And with almost no code!

 

Additional Security Considerations

Do not run Introspection or Playground in production. 

Consider fronting your GraphQL endpoint with an APIM to validate auth. tokens.

If you're looking for an easy way to require authentication to access the GraphQL implement EasyAuth.

 

 

What's Next?
Now that you know you can run Apollo Server in Azure for a very very low cost you should use it!   More articles coming soon about #GraphQL. 

Go further with GraphQL with these additional examples:

A working Apolloo GraphQL Server as a Function used for NurseHack4Health

Building Scalable APIs with GraphQL

Advanced GraphQL and why you should use it with Healthcare data.

 

Em OpsEm Ops

 

 

Posted at https://sl.advdat.com/2WLwyFs