{"id":18248206,"url":"https://github.com/serverless-components/graphql","last_synced_at":"2025-04-04T15:32:16.691Z","repository":{"id":55087933,"uuid":"186831554","full_name":"serverless-components/graphql","owner":"serverless-components","description":"⚡ Deploy and manage GraphQL applications on serverless infrastructure easily, cheaply and scale massively.","archived":false,"fork":false,"pushed_at":"2021-02-23T11:55:40.000Z","size":89,"stargazers_count":50,"open_issues_count":12,"forks_count":3,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-20T15:01:36.777Z","etag":null,"topics":["aws","aws-appsync","aws-lambda","graphql","serverless","serverless-components","serverless-graphql"],"latest_commit_sha":null,"homepage":"https://serverless.com","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/serverless-components.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-05-15T13:25:31.000Z","updated_at":"2023-09-03T16:10:18.000Z","dependencies_parsed_at":"2022-08-14T11:40:14.186Z","dependency_job_id":null,"html_url":"https://github.com/serverless-components/graphql","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/serverless-components%2Fgraphql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/serverless-components%2Fgraphql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/serverless-components%2Fgraphql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/serverless-components%2Fgraphql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/serverless-components","download_url":"https://codeload.github.com/serverless-components/graphql/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247203043,"owners_count":20900900,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws","aws-appsync","aws-lambda","graphql","serverless","serverless-components","serverless-graphql"],"created_at":"2024-11-05T09:36:15.461Z","updated_at":"2025-04-04T15:32:11.682Z","avatar_url":"https://github.com/serverless-components.png","language":"JavaScript","readme":"# Serverless GraphQL Component\n\nThis Serverless Framework Component is a specialized developer experience focused on making it easy to deploy and manage GraphQL applications on serverless infrastructure (specifically AWS AppSync and AWS Lambda) on your own AWS account. It comes loaded with powerful development features and represents possibly the easiest, cheapest and most scalable way to host GraphQL apps.\n\n\u003cbr/\u003e\n\n- [x] **Never Pay For Idle** - No requests, no cost. Averages $0.0000002-$0.0000009 per request.\n- [x] **Zero Configuration** - All we need is your code, then just deploy (advanced config options are available).\n- [x] **Fast Deployments** - Deploy to the cloud in seconds.\n- [x] **Realtime Logging** - Rapidly develop on the cloud w/ real-time logs and errors in the CLI.\n- [x] **Team Collaboration** - Collaborate with your teammates with shared state and outputs.\n- [x] **Custom Domain + SSL** - Auto-configure a custom domain w/ a free AWS ACM SSL certificate.\n- [x] **Lambda Default Resolver** - Automatically deploys your code to a lambda function for rapid query resolution.\n- [x] **Works with All Data Sources** - Can be configured to work with directly with DynamodDB, and other data sources.\n- [x] **Flexible Authorization Options** - Supports all AppSync authorization options, API Key, IAM, Cognito or OpenID auth.\n\n\u003cbr/\u003e\n\n# Contents\n\n- [**Quick Start**](#quick-start)\n  - [**Install**](#install)\n  - [**Initialize**](#initialize)\n  - [**Deploy**](#deploy)\n  - [**Query**](#query)\n- [**Configuration Reference**](#configuration-reference)\n  - [**Extend Existing API**](#extend-existing-api)\n  - [**Lambda Configuration**](#lambda-configuration)\n  - [**Custom Domain**](#custom-domain)\n  - [**Custom IAM Policies**](#custom-iam-policies)\n  - [**Authorization**](#authorization)\n  - [**Data Sources Resolvers**](#data-sources-resolvers)\n- [**CLI Reference**](#cli-reference)\n- [**Outputs Reference**](#outputs-reference)\n- [**FAQs**](#faqs)\n\n# Quick Start\n\n## Install\n\nTo get started with this component, install the latest version of the Serverless Framework:\n\n```\nnpm install -g serverless\n```\n\nAfter installation, make sure you connect your AWS account by setting a provider in the org setting page on the [Serverless Dashboard](https://app.serverless.com).\n\n## Initialize\n\nThe easiest way to start using the graphql component is by initializing the `graphql-starter` template. Just run this command:\n\n```\nserverless init graphql-starter\ncd graphql-starter\n```\n\nThis will also run `npm install` for you. You should now have a directory that looks something like this:\n\n```\n|- serverless.yml\n|- schema.graphql\n|- resolvers.js\n```\n\nThe `serverless.yml` file is where you define your component config. It looks something like this:\n\n```yml\ncomponent: graphql\nname: graphql-api\n\ninputs:\n  src: ./\n```\n\nFor more configuration options for the `serverless.yml` file, [check out the Configuration section](#configuration-reference) below.\n\nThe `schema.graphql` is where you define your GraphQL schema. It looks something like this:\n\n```graphql\ntype Post {\n  id: ID!\n}\n\ntype Query {\n  getPost(id: ID!): Post\n}\n\ntype Mutation {\n  createPost(id: ID!): Post\n}\n\nschema {\n  query: Query\n  mutation: Mutation\n}\n```\n\nThe `resolvers.js` file is where you define your schema resolvers. It looks something like this:\n\n\n```js\nconst Query = {\n  // resolver for field getPost in type Query\n  getPost: async ({ id }) =\u003e {\n    return { id }\n  }\n}\n\nconst Mutation = {\n  // resolver for field createPost in type Mutation\n  createPost: async ({ id }) =\u003e {\n    return { id }\n  }\n}\n\nmodule.exports = { Query, Mutation }\n\n\n```\nIn this file, you simply export each of your schema types (ie. `Query` \u0026 `Mutation`) as an object of functions. Each function is a field resolver for that type.\n\n**All these files are required**. Needless to say, any resolver you define in `resolvers.js`, must also be defined in your schema in the `schema.graphql` file, otherwise, you'll get an AppSync error. Same goes for the resolvers inputs \u0026 outputs. Remember, GraphQL is strongly typed by design.\n\n## Deploy\n\nOnce you have the directory set up, you're now ready to deploy. Just run the following command from within the directory containing the `serverless.yml` file:\n\n```\nserverless deploy\n```\n\nYour first deployment might take a little while, but subsequent deployment would just take few seconds.\n\nAfter deployment is done, you should see your the following outputs:\n\n```yml\nname:   graphql-api-pxzaf135\napiKey: da2-yf444kxlhjerxl376jxyafb2rq\napiId:  survbmoad5ewtnm3e3cd7qys4q\nurl:    https://cnbfx5zutbe4fkrtsldsrunbuu.appsync-api.us-east-1.amazonaws.com/graphql\n```\n\nYour GraphQL API is now deployed! Next time you deploy, if you'd like to know what's happening under the hood and see realtime logs, you can pass the `--debug` flag:\n\n```\nserverless deploy --debug\n```\n\n## Query\n\nYou can query and test your newly created GraphQL API directly with the AWS AppSync console, or any HTTP client. \n\nHere's a snippet using `fetch` or `node-fetch` with the example above:\n\n```js\n// you can get the url and apiKey values from the deployment outputs\nconst url = 'https://cnbfx5zutbe4fkrtsldsrunbuu.appsync-api.us-east-1.amazonaws.com/graphql'\nconst apiKey = 'da2-yf444kxlhjerxl376jxyafb2rq'\n\nfetch(url, {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n    'x-api-key': apiKey // the \"x-api-key\" header is required by AppSync\n  },\n  body: JSON.stringify({\n    query: `query getPost { getPost(id: \"123\") { id }}`\n  })\n})\n  .then((res) =\u003e res.json())\n  .then((post) =\u003e console.log(post))\n```\n\nThe response should be an echo of the post id, something like this:\n\n```json\n{\n  \"data\": {\n    \"getPost\": {\n      \"id\": \"123\"\n    }\n  }\n}\n```\n\n# Configuration Reference\n\nThe GraphQL component is a zero configuration component, meaning that it'll work out of the box with no configuration and sane defaults. With that said, there are still a lot of optional configuration that you can specify.\n\nHere's a very minimal configuration to get you started. Most of these properties are optional, but if you use them, remember to substitute with your own value if required (ie. the `org` property)\n\n```yml\ncomponent: graphql               # (required) name of the component. In that case, it's graphql.\nname: graphql-api                # (required) name of your graphql component instance.\norg: serverlessinc               # (optional) serverless dashboard org. default is the first org you created during signup.\napp: myApp                       # (optional) serverless dashboard app. default is the same as the name property.\nstage: dev                       # (optional) serverless dashboard stage. default is dev.\n\ninputs:\n  src: ./                        # (optional) path to the source folder. default is a simple blogging app.\n  region: us-east-2              # (optional) aws region to deploy to. default is us-east-1.\n```\n\nEven the `src` input is optional. If you didn't specify any `src` directory containing your code, an example app will be deployed for you.\n\nKeep reading to learn more about all the configuration options available to you.\n\n## Extend Existing API\n\nIf the `appId` input variable is provided this component will extend an existing AppSync API:\n\n```yml\ninputs:\n  src: ./\n  apiId: xxx                     # (optional) if provided will extend an existing api.\n```\n\nThe `apiId` can be reference from the source component using the `apiId` output variable from the component instance that created the graphql API: `${output:[STAGE]:[APP]:[NAME].apiId}`\n\n## Lambda Configuration\n\nIf you specify resolvers in a `resolvers.js` file as shown in the quick start above, the component will deploy a lambda function automatically for you to host your resolvers and connect everything together. You can configure this default lambda function with the following inputs:\n\n```yml\ninputs:\n  src: ./\n  description: My GraphQL App    # (optional) lambda description. default is en empty string.\n  memory: 512                    # (optional) lambda memory size. default is 3008.\n  timeout: 10                    # (optional) lambda timeout. default is 300.\n  env:                           # (optional) env vars. default is an empty object\n    TABLE: 'my-table'\n  layers:                        # (optional) list of lambda layer arns to attach to your lambda function.\n    - arn:aws:first:layer\n    - arn:aws:second:layer\n  vpcConfig:                     # (optional) specify a vpc\n    securityGroupIds:\n      - sg-xxx\n    subnetIds:\n      - subnet-xxx\n      - subnet-xxx\n```\n\n## Custom Domain\n\nIf you've purchased your domain from AWS Route53, you can configure the domain with a single input:\n\n```yml\ninputs:\n  src: ./\n  domain: example.com\n```\n\nSubdomains work too:\n\n```yml\ninputs:\n  src: ./\n  domain: api.example.com\n```\n\nThis will create a a free SSL certificate for you with AWS ACM, deploy a CDN with AWS CloudFront, and setup all the DNS records required.\n\nIf you've purchased your domain elsewhere, you'll have to manually create a Route53 hosted zone for your domain, and point to the AWS nameservers on your registrar before you add the `domain` input.\n\n## Custom IAM Policies\n\nThe component creates the minimum required IAM policy based on your configuration. But you could always add your own policy statements using the `policy` input:\n\n```yml\ninputs:\n  src: ./src\n  policy:\n    - Action: '*'\n      Effect: Allow\n      Resource: '*'\n```\n\nThis policy applies to both the built-in Lambda function and the AppSync API. Keep in mind that this component automatically adds the required IAM policies to invoke your data source depending on your configuration.\n\n## Authorization\n\nThis component uses `apiKey` authorization by default. However all other AppSync authorization options are available via the `auth` input.\n\n`IAM` authorization:\n\n```yml\ninputs:\n  src: ./\n  auth: iam\n```\n\n`Cognito` authorization:\n\n```yml\ninputs:\n  src: ./\n  auth:\n    userPoolId: qwertyuiop\n    defaultAction: ALLOW\n    region: us-east-1\n    appIdClientRegex: qwertyuiop\n```\n\n`OpenID` authorization:\n\n```yml\ninputs:\n  src: ./\n  auth:\n    issuer: qwertyuiop\n    authTTL: 0\n    clientId: wertyuiop\n    iatTTL: 0\n```\n\n## Data Sources Resolvers\n\nIf you'd like to setup your resolvers to use your own existing data sources, you could specify your resolvers as a `serverless.yml` input instead of inside a `resolvers.js` file.\n\nIn that case, you'll need to also specify your own `request` and `response` VTL templates. You could do that directly in `serverless.yml`, or by pointing to a `vtl` file inside of your `src` directory.\n\nHere's an example using an existing lambda as a data source:\n\n```yml\ninputs:\n  src: ./\n  resolvers:\n    Query:                          # this must be a valid type in your schema\n      getPost:                      # this must be a valid resolver in your schmea\n        lambda: my-lambda           # this will set up the my-lambda Lambda as a data source for this resolver\n        request: \u003e                  # the request VTL template for this resolver.\n          { \"version\": \"2017-02-28\", \"operation\": \"Invoke\", \"payload\": $util.toJson($context)  }\n        response: response.vtl      # you could also point to a VTL file relative to your src directory.\n```\n\nThese `request` and `response` properties are required regardless of which data source you are working with, and they're different depending on your schema and your application requirements. Check out the [official AWS docs](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference.html) for more information on the required syntax for each data source.\n\n## Lambda Resolvers\n\n```yml\ninputs:\n  src: ./\n  resolvers:\n    Query:                          \n      getPost:                      \n        lambda: my-lambda\n        request: '{ \"version\": \"2017-02-28\", \"operation\": \"Invoke\", \"payload\": $util.toJson($context)  }'\n        response: '$util.toJson($context.result)'\n```\n\n\n## DynamoDB Resolvers\n\n```yml\ninputs:\n  src: ./\n  resolvers:\n    Query:                          \n      getPost:                      \n        table: my-table\n        request: \u003e\n          {\n              \"version\" : \"2017-02-28\",\n              \"operation\" : \"PutItem\",\n              \"key\" : {\n                  \"id\" : $util.dynamodb.toDynamoDBJson($context.arguments.id)\n              }\n          }\n        response: '$util.toJson($context.result)'\n```\n\n## ElasticSearch Resolvers\n\n```yml\ninputs:\n  src: ./\n  resolvers:\n    Query: \n      getPost:\n        endpoint: https://search-my-sample-data-abbaabba.us-east-1.es.amazonaws.com\n        request: \u003e\n          {\n              \"version\":\"2017-02-28\",\n              \"operation\":\"GET\",\n              \"path\":\"/id/post/_search\",\n              \"params\":{\n                  \"headers\":{},\n                  \"queryString\":{},\n                  \"body\":{\n                      \"from\":0,\n                      \"size\":50\n                  }\n              }\n          }\n        response: \u003e\n          [\n              #foreach($entry in $context.result.hits.hits)\n              #if( $velocityCount \u003e 1 ) , #end\n              $utils.toJson($entry.get(\"_source\"))\n              #end\n          ]\n```\n\n## Relational Database Resolvers\n\n```yml          \ninputs:\n  src: ./\n  resolvers:\n    Query:    \n      getPost: \n        database: my-database\n        dbClusterIdentifier: arn:aws:rds:us-east-1:123456789123:cluster:my-serverless-aurora-postgres-1\n        awsSecretStoreArn: arn:aws:secretsmanager:us-east-1:123456789123:secret:rds-db-credentials/cluster-ABCDEFGHI/admin-aBc1e2\n        relationalDatabaseSourceType: RDS_HTTP_ENDPOINT\n        schema: public\n        request: \u003e\n          {\n              \"version\": \"2018-05-29\",\n                  \"statements\": [\n                      $util.toJson(\"select * from Posts WHERE id='$ctx.args.id'\")\n              ]\n          }\n        response: '$utils.toJson($utils.rds.toJsonObject($ctx.result)[0][0])'\n```\n\n# CLI Reference\n\n## deploy\n\nTo deploy, simply run `deploy` from within the directory containing the `serverless.yml` file:\n\n```\nserverless deploy\n```\n\nIf you'd like to know what's happening under the hood and see realtime logs, you can pass the `--debug` flag:\n\n```\nserverless deploy --debug\n```\n\n\n## dev (dev mode)\n\nInstead of having to run `serverless deploy` everytime you make changes you wanna test, you can enable **dev mode**, which allows the CLI to watch for changes in your source directory as you develop, and deploy instantly on save. \n\nTo enable dev mode, simply run the following command from within the directory containing the `serverless.yml` file:\n\n```\nserverless dev\n```\n\nDev mode also enables live streaming logs from your GraphQL app so that you can see the results of your code changes right away on the CLI as they happen.\n\n## info\n\nAnytime you need to know more about your running GraphQL instance, you can run the following command to view the most critical info:\n\n```\nserverless info\n```\n\nThis is especially helpful when you want to know the outputs of your instances so that you can reference them in another instance. It also shows you the status of your instance, when it was last deployed, how many times it was deployed, and the error message \u0026 stack if the latest deployment failed.\n\nTo dig even deeper, you can pass the `--debug` flag to view the state object of your component instance:\n\n```\nserverless info --debug\n```\n\n## remove\n\nIf you wanna tear down your entire GraphQL infrastructure that was created during deployment, just run the following command in the directory containing the `serverless.yml` file:\n\n```\nserverless remove\n```\n\nThe GraphQL component will then use all the data it needs from the built-in state storage system to delete only the relavent cloud resources that it created.\n\nJust like deployment, you could also specify a `--debug` flag for realtime logs from the GraphQL component running in the cloud:\n\n```\nserverless remove --debug\n```\n\n# Outputs Reference\n\n```yml\nname:   graphql-api-pxzaf135\napiKey: da2-yf444kxlhjerxl376jxyafb2rq\napiId:  survbmoad5ewtnm3e3cd7qys4q\nurl:    https://cnbfx5zutbe4fkrtsldsrunbuu.appsync-api.us-east-1.amazonaws.com/graphql\n```\n\n# FAQs\n\n## How do I add NPM packages to the resolvers?\n\nYou can run `npm init` \u0026 `npm install` as you normally would in the directory containing the `resolvers.js` file. This is the root of your app. This entire directory is uploaded to your Lambda function, and you can structure it however you want. Just make sure `resolvers.js` and `schema.graphql` are in the root of the directory.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fserverless-components%2Fgraphql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fserverless-components%2Fgraphql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fserverless-components%2Fgraphql/lists"}