• 沒有找到結果。

Scalar types in AWS AppSync

在文檔中 AWS AppSync (頁 24-31)

Note that the Comment type has the todoid that it’s associated with, commentid, and content. This corresponds to a primary key + sort key combination in the Amazon DynamoDB table you create later.

The application graph on top of your existing data sources in AWS AppSync enables you to return data from two separate data sources in a single GraphQL query. In the example, the assumption is that there is both a Todos table and a Comments table. We’ll show how to do this in Attaching a Data Source (p. 26) and Configuring Resolvers (p. 29).

Scalar types in AWS AppSync

A GraphQL object type has a name and fields, and those fields can have sub-fields. Ultimately, an object type's fields must resolve to scalar types, which represent the leaves of the query. For more information about object types and scalars, see Schemas and Types on the GraphQL website.

In addition to a default set of GraphQL scalars, AWS AppSync includes a set of reserved scalars that start with an AWS prefix. AWS AppSync does not support custom scalars.

NoteYou cannot use AWS as a prefix for custom object types.

GraphQL defines the following default scalars:

ID

A unique identifier for an object. This scalar is serialized like a String but isn't meant to be human-readable.

String

A UTF-8 character sequence.

Int

An integer value between -(231) and 231-1.

Float

An IEEE 754 floating point value.

Boolean

A Boolean value, either true or false.

AWS AppSync defines the following scalars:

AWSDate

An extended ISO 8601 date string in the format YYYY-MM-DD.

AWSTime

An extended ISO 8601 time string in the format hh:mm:ss.sss.

AWSDateTime

An extended ISO 8601 date and time string in the format YYYY-MM-DDThh:mm:ss.sssZ.

NoteThe AWSDate, AWSTime, and AWSDateTime scalars can optionally include a time zone offset.

For example, the values 1970-01-01Z, 1970-01-01-07:00, and 1970-01-01+05:30 are all valid for AWSDate. The time zone offset must be either Z (UTC) or an offset in hours and minutes (and, optionally, seconds). For example, ±hh:mm:ss. The seconds field in the time zone offset is considered valid even though it's not part of the ISO 8601 standard.

Scalar types

AWSTimestamp

An integer value representing the number of seconds before or after 1970-01-01-T00:00Z.

AWSEmail

An email address in the format local-part@domain-part as defined by RFC 822.

AWSJSON

A JSON string. Any valid JSON construct is automatically parsed and loaded in the resolver mapping templates as maps, lists, or scalar values rather than as the literal input strings. Unquoted strings or otherwise invalid JSON result in a GraphQL validation error.

AWSPhone

A phone number. This value is stored as a string. Phone numbers can contain either spaces or hyphens to separate digit groups. Phone numbers without a country code are assumed to be US/

North American numbers adhering to the North American Numbering Plan (NANP).

AWSURL

A URL as defined by RFC 1738. For example, https://www.amazon.com/dp/B000NZW3KC/ or mailto:[email protected]. URLs must contain a schema (http, mailto) and can't contain two forward slashes (//) in the path part.

AWSIPAddress

A valid IPv4 or IPv6 address. IPv4 addresses are expected in quad-dotted notation (123.12.34.56).

IPv6 addresses are expected in non-bracketed, colon-separated format (1a2b:3c4b::1234:4567).

You can include an optional CIDR suffix (123.45.67.89/16) to indicate subnet mask.

Schema usage example

If you're unfamiliar with creating GraphQL APIs in AWS AppSync, or with connecting resolvers with mapping templates, we recommend first reviewing Designing a GraphQL API (p. 11) and Resolver tutorials (p. 51).

The following example GraphQL schema uses all of the custom scalars as an "object" and shows the resolver request and response templates for basic put, get, and list operations. Finally, the example shows how you can use this when running queries and mutations.

type Mutation { putObject(

email: AWSEmail, json: AWSJSON, date: AWSDate, time: AWSTime,

datetime: AWSDateTime, timestamp: AWSTimestamp, url: AWSURL,

phoneno: AWSPhone, ip: AWSIPAddress ): Object

}

type Object { id: ID!

email: AWSEmail json: AWSJSON date: AWSDate time: AWSTime

datetime: AWSDateTime timestamp: AWSTimestamp

Scalar types

url: AWSURL phoneno: AWSPhone ip: AWSIPAddress }

type Query {

getObject(id: ID!): Object listObjects: [Object]

}

schema {

query: Query mutation: Mutation }

Use the following request template for putObject:

{

"version" : "2017-02-28", "operation" : "PutItem", "key" : {

"id": $util.dynamodb.toDynamoDBJson($util.autoId()), },

"attributeValues" : $util.dynamodb.toMapValuesJson($ctx.args) }

The response template for putObject is:

$util.toJson($ctx.result)

Use the following request template for getObject:

{

"version": "2017-02-28", "operation": "GetItem", "key": {

"id": $util.dynamodb.toDynamoDBJson($ctx.args.id), }

}

The response template for getObject is:

$util.toJson($ctx.result)

Use the following request template for listObjects:

{ "version" : "2017-02-28", "operation" : "Scan", }

The response template for listObjects is:

$util.toJson($ctx.result.items)

The following are some examples of using this schema with GraphQL queries:

mutation CreateObject {

Interfaces and unions in GraphQL

putObject(email: "[email protected]"

json: "{\"a\":1, \"b\":3, \"string\": 234}"

date: "1970-01-01Z"

time: "12:00:34."

datetime: "1930-01-01T16:00:00-07:00"

timestamp: -123123 url:"https://amazon.com"

phoneno: "+1 555 764 4377"

ip: "127.0.0.1/8"

) { id email json date time datetime url timestamp phoneno ip } }

query getObject {

getObject(id:"0d97daf0-48e6-4ffc-8d48-0537e8a843d2"){

email url timestamp phoneno ip } }

query listObjects { listObjects { json date time datetime }

}

Interfaces and unions in GraphQL

This topic provides an overview of interface and union types in GraphQL.

Interfaces

The GraphQL type system supports Interfaces. An interface exposes a certain set of fields that a type must include to implement the interface. If you are just getting started with GraphQL, you should return to this topic at a later time when you want to evolve your schema or add more features. To simplify getting started with GraphQL, learn how to automatically create and connect resolvers (p. 43) from a schema.

For example, we could represent an Event interface that represents any kind of activity or gathering of people. Possible kinds of events are Concert, Conference, and Festival. These types all share common characteristics, including a name, a venue where the event is taking place, and a start and end date. These types also have differences, a Conference offers a list of speakers and workshops, while a Concert features a performing band.

In Schema Definition Language (SDL), the Event interface is defined as follows:

Interfaces and unions in GraphQL

interface Event { id: ID!

name : String!

startsAt: String endsAt: String venue: Venue

minAgeRestriction: Int }

And each of the types implements the Event interface as follows:

type Concert implements Event { id: ID!

name: String!

startsAt: String endsAt: String venue: Venue

minAgeRestriction: Int performingBand: String }

type Festival implements Event { id: ID!

name: String!

startsAt: String endsAt: String venue: Venue

minAgeRestriction: Int performers: [String]

}

type Conference implements Event { id: ID!

name: String!

startsAt: String endsAt: String venue: Venue

minAgeRestriction: Int speakers: [String]

workshops: [String]

}

Interfaces are useful to represent elements that might be of several types. For example, we could search for all events happening at a specific venue. Let’s add a findEventsByVenue field to the schema as follows:

schema {

query: Query }

type Query {

# Retrieve Events at a specific Venue findEventsAtVenue(venueId: ID!): [Event]

}

type Venue { id: ID!

name: String address: String maxOccupancy: Int }

Interfaces and unions in GraphQL

type Concert implements Event { id: ID!

name: String!

startsAt: String endsAt: String venue: Venue

minAgeRestriction: Int performingBand: String }

minAgeRestriction: Int }

type Festival implements Event { id: ID!

name: String!

startsAt: String endsAt: String venue: Venue

minAgeRestriction: Int performers: [String]

}

type Conference implements Event { id: ID!

name: String!

startsAt: String endsAt: String venue: Venue

minAgeRestriction: Int speakers: [String]

workshops: [String]

}

findEventsByVenue returns a list of Event. Because GraphQL interface fields are common to all the implementing types, it’s possible to select any fields on the Event interface (id, name, startsAt, endsAt, venue, and minAgeRestriction). Additionally, you can access the fields on any implementing type using GraphQL fragments, as long as you specify the type.

Let’s examine an example of a GraphQL query that uses the interface.

query {

findEventsAtVenue(venueId: "Madison Square Garden") { id

name

minAgeRestriction startsAt

Interfaces and unions in GraphQL

workshops }

}}

The previous query yields a single list of results, and the server could sort the events by start date by default.

{ "data": {

"findEventsAtVenue": [ {

"id": "Festival-2", "name": "Festival 2", "minAgeRestriction": 21,

"startsAt": "2018-10-05T14:48:00.000Z", "performers": [

"The Singers", "The Screamers"

] }, {

"id": "Concert-3", "name": "Concert 3", "minAgeRestriction": 18,

"startsAt": "2018-10-07T14:48:00.000Z", "performingBand": "The Jumpers"

}, {

"id": "Conference-4", "name": "Conference 4", "minAgeRestriction": null,

"startsAt": "2018-10-09T14:48:00.000Z", "speakers": [

"The Storytellers"

],

"workshops": [ "Writing", "Reading"

] } ] } }

Since results are returned as a single collection of events, using interfaces to represent common characteristics is very helpful for sorting results.

Unions

The GraphQL type system also supports Unions. Unions are identical to interfaces, except that they don’t define a common set of fields. Unions are generally preferred over interfaces when the possible types do not share a logical hierarchy.

For example, a search result might represent many different types. Using the Event schema, you can define a SearchResult union as follows:

type Query {

# Retrieve Events at a specific Venue findEventsAtVenue(venueId: ID!): [Event]

# Search across all content

search(query: String!): [SearchResult]

Interfaces and unions in GraphQL

}

union SearchResult = Conference | Festival | Concert | Venue

In this case, to query any field on our SearchResult union, you must use fragments. Let’s examine the following example:

query {

search(query: "Madison") { ... on Venue {

id name address }

... on Festival { id

name performers }

... on Concert { id

name

performingBand }

... on Conference { speakers

workshops }

} }

在文檔中 AWS AppSync (頁 24-31)

相關文件