Implementation here.
In this example, the backend implements handling of visitor badges. Each badge is issued with a unique ID when a person arrives to the office. Then the badge tracks how many times it was used and its lifecycle ends when it is returned.
The backend defines a subscription for when badges are issued, used, and returned. Then it also defines a query that returns badges ordered by their last updated time decreasing. Importantly, this query supports the onlyActive
argument to fetch only non-returned badges.
The schema implementation:
type Badge {
id: ID!
issued_at: AWSDateTime!
returned_at: AWSDateTime
last_updated: AWSDateTime!
use_count: Int!
}
type BadgeConnection {
items: [Badge!]!
nextToken: String
}
type Subscription {
badge: Badge
}
type Query {
badges(onlyActive: Boolean!, nextToken: String): BadgeConnection!
}
The onlyActive
argument for the query is important here because the item fetches are different whether it's for a page load or after a reconnection. The initial fetch needs only the active badges. But then after a reconnection, the client needs to download updates for all badges, even when they are returned in the meantime.
The ordering of the results is also important. While the initial query fetches all active badges, after reconnection only the updates after the last time the client was up-to-date with the backend needs to be returned. To avoid fetching all badges (an operation that potentially returns a large number of items), the client can fetch only the updates it missed.
Then the client shows an up-to-date list of badges:
The function we'll write is similar to the previous ones: an observable that emits updates:
updates({
opened: () => setSubscriptionStatus(true),
closed: () => setSubscriptionStatus(false),
}).subscribe((updates) => handleUpdate(updates));