Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Completed class for my tutorial 'Fetching all your data from AWS AppSync'
class OrderService {
static let shared = OrderService()
private var appSyncClient: AWSAppSyncClient?
public var orders: [Order] = []
private init() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appSyncClient = appDelegate.appSyncClient
}
func fetchOrders(nextToken: String?=nil, _ completion: @escaping (Swift.Result<Result, Error>) -> Void) {
appSyncClient?.fetch(
query: ListOrdersQuery(limit: 1000, nextToken: nextToken), cachePolicy: .fetchIgnoringCacheData
) { (result, error) in
if let error = error {
completion(.failure(error))
} else {
if let items = result?.data?.listOrders?.items {
for item in items {
self.orders.append(Order(
id: item?.id,
sku: item?.sku,
price: item?.price
))
}
}
if let nextToken = result?.data?.listOrders?.nextToken {
self.fetchOrders(nextToken: nextToken) { result in
completion(result)
}
} else {
completion(.success("Completed fetching!")) }
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment