Add real-time data to your app

realtime

1. Define a new model for real-time race data

Start by defining a new model for your real-time race data. Open the file amplify/backend/api/graphqlrealtimerace/schema.graphql and add the following RaceEvent model definition and a new subscription onReceiveRaceEvent.

type RaceEvent 
  @model 
  @key(
    fields: ["eventId", "createdAt"]
    name: "ByEventId"
    queryField: "raceEventsByEventId"
  )
  @auth(
    rules: [{allow: private, provider: iam, operations: [read, create]}, {allow: private, operations: [read]}]
  ) {
  id: ID!
  event: Event @connection(fields: ["eventId"])
  eventId: ID
  type: String
  competitor: String
  lap: Int
  time: String
  position: Int
  speed: Int
  gear: Int
  longitude: Float
  latitude: Float
  createdAt: AWSDateTime!
  updatedAt: AWSDateTime!
}

type Subscription {
  onMutateMessage(eventId: ID): Message
    @aws_subscribe(mutations: ["createMessage", "updateMessage"])
  onReceiveRaceEvent(eventId: ID): RaceEvent
    @aws_subscribe(mutations: ["createRaceEvent"])
}

A RaceEvent is associated with an Event, leveraging the @connection(fields: ["eventId"]) directive. Users are able to select an event and see race updates that are happening in real-time. We also specify the eventId argument to tell AppSync how to filter the subscription before sending it to the user. In this case, a user can subscribe to receive real time notifications for race updates that belong to as specific event.

The type uses the @auth directive to create 2 rules:

  1. {allow: private, operations: [read]}: allows all signed-in cognito users to read race events. This is needed to allow users to see race updates in the app
  2. {allow: private, provider: iam, operations: [read, create]}: allows IAM credential users to create and read events. This is needed to allow a Lambda function to add race events

Deploy your changes from the cli:

amplify push --yes