Come creare e distribuire un server GraphQL in AWS Lambda utilizzando Node.js e CloudFormation

introduzione

Ho creato API GraphQL in un ambiente Serverless da oltre 3 anni. Non riesco nemmeno più a immaginare di lavorare con le API RESTful. Combina la potenza di GraphQL con la scalabilità di AWS Lambda e avrai un server in grado di gestire quantità infinite di traffico.

In questo tutorial, costruiremo e distribuiremo un server GraphQL in AWS Lambda e vi accederemo tramite un endpoint API Gateway. Useremo CloudFormation e AWS CLI per distribuire tutte le nostre risorse AWS e il codice dell'applicazione.

Cosa tratteremo

  1. Crea un server GraphQL utilizzando Apollo
  2. Distribuisci quel server GraphQL su Lambda
  3. Utilizza API Gateway per eseguire il proxy delle richieste a Lambda
  4. Utilizza CloudFormation per distribuire lo stack di applicazioni in AWS
  5. Imposta Lambda per lo sviluppo locale.

TL; DR: è possibile ottenere il codice sorgente completo per l'applicazione da Github.

Cos'è GraphQL?

GraphQL è un linguaggio di query per descrivere le API utilizzando un sistema di schemi fortemente tipizzato. Un server GraphQL soddisfa queste richieste utilizzando i dati esistenti. Di seguito sono riportati alcuni dei principali vantaggi dell'utilizzo di GraphQL.

Interroga solo ciò di cui la tua applicazione ha bisogno

A differenza delle API REST, GraphQL consente ai client di eseguire query con precisione e solo ciò di cui hanno bisogno. Il server soddisfa la richiesta del client restituendo solo ciò che il client richiede.

GraphQL utilizza un sistema fortemente tipizzato

Il sistema fortemente tipizzato di GraphQL consente agli utenti di esaminare l'intero schema. E l'API GraphQL funge da documentazione chiara sulle capacità del server e ti informa sugli errori durante lo sviluppo.

Puoi comporre le tue domande in un'unica richiesta

Con GraphQL, puoi eseguire query su più risorse e ottenere risposte combinate con una singola richiesta. Con meno richieste, le app che utilizzano GraphQL funzionano molto più velocemente.

Cos'è AWS Lambda?

AWS Lambda è un servizio di elaborazione offerto da AWS che ti consente di eseguire il codice dell'applicazione senza dover gestire alcun server. AWS gestisce tutto l'overhead come infrastruttura, sicurezza, risorse, sistema operativo e patch in modo che gli sviluppatori possano concentrarsi solo sulla creazione dell'applicazione.

Iniziamo…

Impostazione del progetto

Cominciamo creando una cartella del progetto. Quindi, passare alla directory e inizializzare un progetto Node. Sto usando node 10.xnegli esempi. Puoi installare la versione di Node che preferisci usando asdf.

mkdir apollo-server-lambda-nodejs cd apollo-server-lambda-nodejs yarn init

Successivamente, crea una cartella che ospita tutto il nostro codice sorgente.

mkdir src

Infine, crea un file di indice all'interno della srcdirectory che funge da gestore lambda.

cd src touch index.js

Popolare il file di indice con il codice seguente.

exports.handler = async () => { return { body: 'Hello from Lambda' }; };

Il codice precedente è un gestore Lambda molto semplice che restituirà una Hello from Lambdavolta richiamato. Distribuiamo prima il nostro codice in AWS Lambda.

Creare il pacchetto del codice dell'applicazione

Prima di poter distribuire il nostro codice su Lambda, dobbiamo creare uno zip della nostra applicazione e caricarlo in un bucket S3. Stiamo utilizzando AWS CLI per creare il bucket. Configura AWS CLI ora seguendo questa guida, se non l'hai già fatto.

Crea un bucket S3 da utilizzare per distribuire il nostro codice su Lambda. Scegli un nome univoco per il tuo bucket S3. I nomi dei bucket sono univoci a livello globale in tutte le regioni AWS.

aws s3 mb s3://lambda-deploy-asln

Crea un archivio dell'applicazione utilizzando il comando zip e verifica i file all'interno dello zip.

zip -rq dist-latest.zip src package.json zipinfo dist-latest.zip

Copia il file zip su S3 utilizzando il comando AWS CLI.

aws s3 cp dist-latest.zip s3://lambda-deploy-asln/dist-latest.zip

Infine, utilizza il seguente comando per verificare che il file esista in S3.

aws s3 ls s3://lambda-deploy-asln

Ora che abbiamo distribuito l'applicazione in pacchetto su S3, dobbiamo configurare Lambda e API Gateway in AWS. Nella sezione successiva, utilizzeremo CloudFormation per configurare tutte le risorse AWS necessarie.

Configura AWS lambda con l'integrazione del proxy del gateway API

CloudFormation è un servizio AWS che ci aiuta a scrivere l'infrastruttura come codice. CloudFormation rende molto semplice creare e gestire le nostre risorse applicative. Usiamo CloudFormation per definire il nostro stack.

Crea un file denominato cloudformation.ymlnella radice del progetto.

touch cloudformation.yml

Aggiungi il codice seguente al file cloudformation.yml

--- Description: GraphQL server on AWS lambda Parameters: Version: Description: Application version number Type: String BucketName: Description: S3 bucket name where the source code lives Type: String Resources: LambdaFunction: Type: AWS::Lambda::Function Properties: Code: S3Bucket: !Ref BucketName S3Key: !Sub dist-${Version}.zip Handler: src/index.handler Description: GraphQL Apollo Server Role: !GetAtt LambdaExecutionRole.Arn Runtime: nodejs10.x Timeout: 10 LambdaExecutionRole: Type: "AWS::IAM::Role" Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Principal: Service: - "lambda.amazonaws.com" Action: - "sts:AssumeRole" Policies: - PolicyName: "LambdaFunctionPolicy" PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: "*" GraphQLApi: Type: 'AWS::ApiGateway::RestApi' Properties: Name: apollo-graphql-api GraphQLApiResource: Type: 'AWS::ApiGateway::Resource' Properties: ParentId: !GetAtt GraphQLApi.RootResourceId RestApiId: !Ref GraphQLApi PathPart: 'graphql' GraphQLApiMethod: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref GraphQLApi ResourceId: !Ref GraphQLApiResource AuthorizationType: None HttpMethod: POST Integration: Type: AWS_PROXY IntegrationHttpMethod: POST Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/invocations GraphQLApiDeployment: Type: 'AWS::ApiGateway::Deployment' Properties: RestApiId: !Ref GraphQLApi StageName: v1 DependsOn: - GraphQLApiResource - GraphQLApiMethod GraphQLApiPermission: Type: 'AWS::Lambda::Permission' Properties: Action: lambda:invokeFunction FunctionName: !GetAtt LambdaFunction.Arn Principal: apigateway.amazonaws.com SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${GraphQLApi}/* Outputs: ApiUrl: Description: Invoke url of API Gateway endpoint Value: !Sub //${GraphQLApi}.execute-api.${AWS::Region}.amazonaws.com/v1/graphql

So che stanno accadendo molte cose in questo modello. Esaminiamo il codice passo dopo passo.

Parametri del modello

Firstly, we define some parameters that we use in the template. We can pass those variables as parameter overrides when deploying the CloudFormation Stack.

Description: GraphQL server on AWS lambda Parameters: Version: Description: Application version number Type: String BucketName: Description: S3 bucket name where the source code lives Type: String

Lambda Function

We define our lambda function specifying the path from where it should pull the application code. This bucket is the same one we created earlier.

LambdaFunction: Type: AWS::Lambda::Function Properties: Code: S3Bucket: !Ref BucketName S3Key: !Sub dist-${Version}.zip Handler: src/index.handler Description: GraphQL Apollo Server Role: !GetAtt LambdaExecutionRole.Arn Runtime: nodejs10.x Timeout: 10

We want our Lambda function to be able to send application logs to AWS CloudWatch. Lambda requires special permissions to be able to write logs to CloudWatch. So we create a role that enables writing to CloudWatch and assign it to the Lambda function.

LambdaExecutionRole: Type: "AWS::IAM::Role" Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Principal: Service: - "lambda.amazonaws.com" Action: - "sts:AssumeRole" Policies: - PolicyName: "LambdaFunctionPolicy" PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: "*"

API Gateway

We also want an HTTP endpoint to invoke the lambda function. API Gateway can be used to create an HTTP endpoint. We can then configure API Gateway to proxy all incoming requests from the client to the Lambda function and send the response from Lambda back to the client.

In primo luogo, creiamo un API Gateway RestApi.

GraphQLApi: Type: 'AWS::ApiGateway::RestApi' Properties: Name: apollo-graphql-api

Quindi, creiamo una risorsa API Gateway, che accetta le richieste in /graphql.

GraphQLApiResource: Type: 'AWS::ApiGateway::Resource' Properties: ParentId: !GetAtt GraphQLApi.RootResourceId RestApiId: !Ref GraphQLApi PathPart: 'graphql'

Successivamente, configuriamo la risorsa per accettare le richieste POST creando un metodo gateway API e quindi la integriamo con Lambda.

GraphQLApiMethod: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref GraphQLApi ResourceId: !Ref GraphQLApiResource AuthorizationType: None HttpMethod: POST Integration: Type: AWS_PROXY IntegrationHttpMethod: POST Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/invocations

Infine, creiamo una distribuzione API Gateway che distribuisce l'API nella fase specificata.

GraphQLApiDeployment: Type: 'AWS::ApiGateway::Deployment' Properties: RestApiId: !Ref GraphQLApi StageName: v1 DependsOn: - GraphQLApiResource - GraphQLApiMethod

Autorizzazione Lambda / API Gateway

A questo punto, sia la funzione Lambda che il gateway API sono configurati correttamente. Tuttavia, API Gateway necessita di un'autorizzazione speciale per richiamare una funzione Lambda. Consentiamo ad API Gateway di richiamare Lambda creando una risorsa di autorizzazione Lambda.

GraphQLApiPermission: Type: 'AWS::Lambda::Permission' Properties: Action: lambda:invokeFunction FunctionName: !GetAtt LambdaFunction.Arn Principal: apigateway.amazonaws.com SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${GraphQLApi}/*

Infine, esportiamo l'URL dell'API alla fine del modello. Possiamo utilizzare questo URL per richiamare le chiamate a Lambda.

Outputs: ApiUrl: Description: Invoke url of API Gateway endpoint Value: !Sub //${GraphQLApi}.execute-api.${AWS::Region}.amazonaws.com/v1/graphql

Distribuisci lo stack di CloudFormation su AWS

Now that we have the CloudFormation template ready let’s use the AWS CLI command to deploy it to AWS.

Run the following command in your console. Make sure to update the BucketName to whatever the name of the bucket you created earlier is.

aws cloudformation deploy \ --template-file ./cloudformation.yml \ --stack-name apollo-server-lambda-nodejs \ --parameter-overrides BucketName=lambda-deploy-asln Version=latest \ --capabilities CAPABILITY_IAM

It might take some time to deploy the stack. Lambda function should be ready to start taking requests when the deployment finishes.

Verify API Gateway and Lambda are working as expected

Now that we have deployed our CloudFormation Stack let us verify if everything is working as expected. We need the API Gateway URL to send a request to our Lambda Function. The API URL we exported in the CloudFormation template comes in handy here.

Run the following command to print the API URL in the command line.

aws cloudformation describe-stacks \ --stack-name=apollo-server-lambda-nodejs \ --query "Stacks[0].Outputs[?OutputKey=='ApiUrl'].OutputValue" \ --output text 

Now, use the curl command to invoke the API URL. You should get "Hello from Lambda" back from the server.

curl -d '{}' //o55ybz0sc5.execute-api.us-east-1.amazonaws.com/v1/graphql

Add deploy script for easier deployment

You might have noticed that we ran a whole bunch of commands to package and deploy our application. It would be very tedious to have to run those commands every time we deploy the application. Let’s add a bash script to simplify this workflow.

Create a directory called bin at the root of the application and add a file named deploy.

mkdir bin touch bin/deploy

Before we can execute the script, we need to set correct file permissions. Let’s do that by running the following command.

chmod +x bin/deploy

At this point, our directory structure should look like in the screenshot below.

Add the following code to the file.

#!/bin/bash set -euo pipefail OUTPUT_DIR=dist CURRENT_DIR=$(pwd) ROOT_DIR="$( dirname "${BASH_SOURCE[0]}" )"/.. APP_VERSION=$(date +%s) STACK_NAME=apollo-server-lambda-nodejs cd $ROOT_DIR echo "cleaning up old build.." [ -d $OUTPUT_DIR ] && rm -rf $OUTPUT_DIR mkdir dist echo "zipping source code.." zip -rq $OUTPUT_DIR/dist-$APP_VERSION.zip src node_modules package.json echo "uploading source code to s3.." aws s3 cp $OUTPUT_DIR/dist-$APP_VERSION.zip s3://$S3_BUCKET/dist-$APP_VERSION.zip echo "deploying application.." aws cloudformation deploy \ --template-file $ROOT_DIR/cloudformation.yml \ --stack-name $STACK_NAME \ --parameter-overrides Version=$APP_VERSION BucketName=$S3_BUCKET \ --capabilities CAPABILITY_IAM # Get the api url from output of cloudformation stack API_URL=$( aws cloudformation describe-stacks \ --stack-name=$STACK_NAME \ --query "Stacks[0].Outputs[?OutputKey=='ApiUrl'].OutputValue" \ --output text ) echo -e "\n$API_URL" cd $CURRENT_DIR

OK, let’s break down what’s going on in this script.

We start by defining some variables. We generate the archive file inside the dist directory. We set the app version to the current timestamp at which the script runs. Using the timestamp, we can make sure that the version number is always unique and incremental.

#!/bin/bash set -euo pipefail OUTPUT_DIR=dist CURRENT_DIR=$(pwd) ROOT_DIR="$( dirname "${BASH_SOURCE[0]}" )"/.. APP_VERSION=$(date +%s) STACK_NAME=apollo-server-lambda-nodejs

We then clean up any old builds and create a new dist directory.

echo "cleaning up old build.." [ -d $OUTPUT_DIR ] && rm -rf $OUTPUT_DIR mkdir dist

Then we run the zip command to archive the source code and its dependencies.

echo "zipping source code.." zip -rq $OUTPUT_DIR/dist-$APP_VERSION.zip src node_modules package.json

Next, we copy the zip file to the S3 bucket.

echo "uploading source code to s3.." aws s3 cp $OUTPUT_DIR/dist-$APP_VERSION.zip s3://$S3_BUCKET/dist-$APP_VERSION.zip

Then we deploy the CloudFormation stack.

echo "deploying application.." aws cloudformation deploy \ --template-file $ROOT_DIR/cloudformation.yml \ --stack-name $STACK_NAME \ --parameter-overrides Version=$APP_VERSION BucketName=$S3_BUCKET \ --capabilities CAPABILITY_IAM

Finally, we query the CloudFormation Stack to get the API URL from the CloudFormation Outputs and print it in the console.

# Get the api url from output of cloudformation stack API_URL=$( aws cloudformation describe-stacks \ --stack-name=$STACK_NAME \ --query "Stacks[0].Outputs[?OutputKey=='ApiUrl'].OutputValue" \ --output text ) echo -e "\n$API_URL"

Deploy to AWS using the deploy script

Let’s try out the deployment using the deploy script. The script expects the S3_Bucket variable to be present in the environment. Run the following command to run the deployment. When the deployment is successful, the script will output the API URL that we can use to invoke the lambda.

S3_BUCKET=lambda-deploy-asln ./bin/deploy

To simplify this even further, let’s invoke it using yarn. Add the following in your package.json.

"scripts": { "deploy": "S3_BUCKET=lambda-deploy-asln ./bin/deploy" }

Hereafter we can simply run yarn deploy to initiate deployments.

Improve workflow with local Lambda and API Gateway

We frequently modified the application code while working on our application. Right now, deploying to AWS us-east-1 region takes me around 10 seconds. I am on a 40Mb/s upload speed internet connection.

Time to deploy becomes more significant as the size of the application grows. Having to wait 10 seconds or more to realize I have made a syntax error is not productive at all.

Let’s fix this by setting up the lambda function locally and invoke it using a local API Endpoint. AWS SAM CLI enables us to do just that. Follow the instruction on this page to install it.

Once done, from the root of the project, run the following command.

sam local start-api --template-file cloudformation.yml

The local endpoint is now available at //localhost:3000. We can use this endpoint to send requests to our local Lambda.

Open another terminal and run the following command to send a request. You should see the response from our local Lambda function.

curl -d '{}' //localhost:3000/graphql

Finally, add the following lines in the scripts section of the package.json.

"dev": "sam local start-api --template-file cloudformation.yml"

Hereafter we can run the yarn dev command to start the dev server.

Set up the GraphQL server in Lambda

Without further talking, let’s jump right into the code and build the GraphQL server.

Start by installing the dependencies. We are using Apollo Server to build our GraphQL server. Apollo Server is an open-source implementation of GraphQL Server.

yarn add apollo-server-lambda graphql

Replace the content of src/index.js with the following code.

const { ApolloServer, gql } = require('apollo-server-lambda'); const typeDefs = gql` type Query { user: User } type User { id: ID name: String } `; const resolvers = { Query: { user: () => ({ id: 123, name: 'John Doe' }) } }; const server = new ApolloServer({ typeDefs, resolvers }); exports.handler = server.createHandler();

Here, we define a schema which consists of a type User and a user query. We then define a resolver for the user query. For the sake of simplicity, the resolver returns a hardcoded user. Finally, we create a GraphQL handler and export it.

To perform queries to our GraphQL server, we need a GraphQL client. Insomnia is my favourite client. However, any other GraphQL client should be just fine.

Now, let’s run a query to ensure our server is working as expected.

Create a new GraphQL request in Insomnia.

Add the following query in the body and submit the query to //localhost:3000. Assuming your dev server is still running, you should see the following response from the GraphQL server.

Now that we've verified everything is working fine in the local server let’s run the following command to deploy the GraphQL server to AWS.

yarn deploy

The API URL is outputted in the console once the deployment is complete. Replace the URL in Insomnia with the one from API Gateway. Rerun the query to see it resolve.

Summary

Congratulations, you have successfully deployed a GraphQL Server in AWS Lambda purely using CloudFormation. The server can receive GraphQL requests from the client and return the response accordingly.

We also set up the development environment for local development without adding many dependencies.

If you liked this tutorial, please share it with your network.