在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):serverless-components/graphql开源软件地址(OpenSource Url):https://github.com/serverless-components/graphql开源编程语言(OpenSource Language):JavaScript 100.0%开源软件介绍(OpenSource Introduction):Serverless GraphQL ComponentThis 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.
ContentsQuick StartInstallTo get started with this component, install the latest version of the Serverless Framework:
After installation, make sure you connect your AWS account by setting a provider in the org setting page on the Serverless Dashboard. InitializeThe easiest way to start using the graphql component is by initializing the
This will also run
The component: graphql
name: graphql-api
inputs:
src: ./ For more configuration options for the The type Post {
id: ID!
}
type Query {
getPost(id: ID!): Post
}
type Mutation {
createPost(id: ID!): Post
}
schema {
query: Query
mutation: Mutation
} The const Query = {
// resolver for field getPost in type Query
getPost: async ({ id }) => {
return { id }
}
}
const Mutation = {
// resolver for field createPost in type Mutation
createPost: async ({ id }) => {
return { id }
}
}
module.exports = { Query, Mutation }
In this file, you simply export each of your schema types (ie. All these files are required. Needless to say, any resolver you define in DeployOnce you have the directory set up, you're now ready to deploy. Just run the following command from within the directory containing the
Your first deployment might take a little while, but subsequent deployment would just take few seconds. After deployment is done, you should see your the following outputs: name: graphql-api-pxzaf135
apiKey: da2-yf444kxlhjerxl376jxyafb2rq
apiId: survbmoad5ewtnm3e3cd7qys4q
url: https://cnbfx5zutbe4fkrtsldsrunbuu.appsync-api.us-east-1.amazonaws.com/graphql Your 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
QueryYou can query and test your newly created GraphQL API directly with the AWS AppSync console, or any HTTP client. Here's a snippet using // you can get the url and apiKey values from the deployment outputs
const url = 'https://cnbfx5zutbe4fkrtsldsrunbuu.appsync-api.us-east-1.amazonaws.com/graphql'
const apiKey = 'da2-yf444kxlhjerxl376jxyafb2rq'
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey // the "x-api-key" header is required by AppSync
},
body: JSON.stringify({
query: `query getPost { getPost(id: "123") { id }}`
})
})
.then((res) => res.json())
.then((post) => console.log(post)) The response should be an echo of the post id, something like this: {
"data": {
"getPost": {
"id": "123"
}
}
} Configuration ReferenceThe 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. Here'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 component: graphql # (required) name of the component. In that case, it's graphql.
name: graphql-api # (required) name of your graphql component instance.
org: serverlessinc # (optional) serverless dashboard org. default is the first org you created during signup.
app: myApp # (optional) serverless dashboard app. default is the same as the name property.
stage: dev # (optional) serverless dashboard stage. default is dev.
inputs:
src: ./ # (optional) path to the source folder. default is a simple blogging app.
region: us-east-2 # (optional) aws region to deploy to. default is us-east-1. Even the Keep reading to learn more about all the configuration options available to you. Extend Existing APIIf the inputs:
src: ./
apiId: xxx # (optional) if provided will extend an existing api. The Lambda ConfigurationIf you specify resolvers in a inputs:
src: ./
description: My GraphQL App # (optional) lambda description. default is en empty string.
memory: 512 # (optional) lambda memory size. default is 3008.
timeout: 10 # (optional) lambda timeout. default is 300.
env: # (optional) env vars. default is an empty object
TABLE: 'my-table'
layers: # (optional) list of lambda layer arns to attach to your lambda function.
- arn:aws:first:layer
- arn:aws:second:layer
vpcConfig: # (optional) specify a vpc
securityGroupIds:
- sg-xxx
subnetIds:
- subnet-xxx
- subnet-xxx Custom DomainIf you've purchased your domain from AWS Route53, you can configure the domain with a single input: inputs:
src: ./
domain: example.com Subdomains work too: inputs:
src: ./
domain: api.example.com This 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. If 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 Custom IAM PoliciesThe component creates the minimum required IAM policy based on your configuration. But you could always add your own policy statements using the inputs:
src: ./src
policy:
- Action: '*'
Effect: Allow
Resource: '*' This 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. AuthorizationThis component uses
inputs:
src: ./
auth: iam
inputs:
src: ./
auth:
userPoolId: qwertyuiop
defaultAction: ALLOW
region: us-east-1
appIdClientRegex: qwertyuiop
inputs:
src: ./
auth:
issuer: qwertyuiop
authTTL: 0
clientId: wertyuiop
iatTTL: 0 Data Sources ResolversIf you'd like to setup your resolvers to use your own existing data sources, you could specify your resolvers as a In that case, you'll need to also specify your own Here's an example using an existing lambda as a data source: inputs:
src: ./
resolvers:
Query: # this must be a valid type in your schema
getPost: # this must be a valid resolver in your schmea
lambda: my-lambda # this will set up the my-lambda Lambda as a data source for this resolver
request: > # the request VTL template for this resolver.
{ "version": "2017-02-28", "operation": "Invoke", "payload": $util.toJson($context) }
response: response.vtl # you could also point to a VTL file relative to your src directory. These Lambda Resolversinputs:
src: ./
resolvers:
Query:
getPost:
lambda: my-lambda
request: '{ "version": "2017-02-28", "operation": "Invoke", "payload": $util.toJson($context) }'
response: '$util.toJson($context.result)' DynamoDB Resolversinputs:
src: ./
resolvers:
Query:
getPost:
table: my-table
request: >
{
"version" : "2017-02-28",
"operation" : "PutItem",
"key" : {
"id" : $util.dynamodb.toDynamoDBJson($context.arguments.id)
}
}
response: '$util.toJson($context.result)' ElasticSearch Resolversinputs:
src: ./
resolvers:
Query:
getPost:
endpoint: https://search-my-sample-data-abbaabba.us-east-1.es.amazonaws.com
request: >
{
"version":"2017-02-28",
"operation":"GET",
"path":"/id/post/_search",
"params":{
"headers":{},
"queryString":{},
"body":{
"from":0,
"size":50
}
}
}
response: >
[
#foreach($entry in $context.result.hits.hits)
#if( $velocityCount > 1 ) , #end
$utils.toJson($entry.get("_source"))
#end
] Relational Database Resolversinputs:
src: ./
resolvers:
Query:
getPost:
database: my-database
dbClusterIdentifier: arn:aws:rds:us-east-1:123456789123:cluster:my-serverless-aurora-postgres-1
awsSecretStoreArn: arn:aws:secretsmanager:us-east-1:123456789123:secret:rds-db-credentials/cluster-ABCDEFGHI/admin-aBc1e2
relationalDatabaseSourceType: RDS_HTTP_ENDPOINT
schema: public
request: >
{
"version": "2018-05-29",
"statements": [
$util.toJson("select * from Posts WHERE id='$ctx.args.id'")
]
}
response: '$utils.toJson($utils.rds.toJsonObject($ctx.result)[0][0])' CLI ReferencedeployTo deploy, simply run
If you'd like to know what's happening under the hood and see realtime logs, you can pass the
dev (dev mode)Instead of having to run To enable dev mode, simply run the following command from within the directory containing the
Dev 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. infoAnytime you need to know more about your running GraphQL instance, you can run the following command to view the most critical info:
This 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 & stack if the latest deployment failed. To dig even deeper, you can pass the
removeIf you wanna tear down your entire GraphQL infrastructure that was created during deployment, just run the following command in the directory containing the
The 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. Just like deployment, you could also specify a
Outputs Referencename: graphql-api-pxzaf135
apiKey: da2-yf444kxlhjerxl376jxyafb2rq
apiId: survbmoad5ewtnm3e3cd7qys4q
url: https://cnbfx5zutbe4fkrtsldsrunbuu.appsync-api.us-east-1.amazonaws.com/graphql FAQsHow do I add NPM packages to the resolvers?You can run |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论