main.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright 2017, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import gRPC
  18. import OAuth2
  19. let CREDENTIALS = "google.json" // in $HOME/.credentials
  20. let TOKEN = "google.json" // local auth token storage
  21. #if os(OSX)
  22. // On OS X, we use the local browser to help the user get a token.
  23. let tokenProvider = try BrowserTokenProvider(credentials:CREDENTIALS, token:TOKEN)
  24. guard let tokenProvider = tokenProvider else {
  25. print("ERROR: Unable to create BrowserTokenProvider.")
  26. exit(-1)
  27. }
  28. if tokenProvider.token == nil {
  29. try tokenProvider.signIn(scopes:["https://www.googleapis.com/auth/datastore"])
  30. try tokenProvider.saveToken(TOKEN)
  31. }
  32. #else
  33. // On Linux, we can get a token if we are running in Google Cloud Shell
  34. // or in some other Google Cloud instance (GAE, GKE, GCE, etc).
  35. let tokenProvider = try GoogleTokenProvider()
  36. #endif
  37. gRPC.initialize()
  38. guard let authToken = tokenProvider.token?.AccessToken else {
  39. print("ERROR: No OAuth token is available.")
  40. exit(-1)
  41. }
  42. let projectID = "your-project-identifier"
  43. let certificateURL = URL(fileURLWithPath:"roots.pem")
  44. let certificates = try! String(contentsOf: certificateURL, encoding: .utf8)
  45. let service = Google_Datastore_V1_DatastoreService(address:"datastore.googleapis.com",
  46. certificates:certificates,
  47. host:nil)
  48. service.metadata = Metadata(["authorization":"Bearer " + authToken])
  49. var request = Google_Datastore_V1_RunQueryRequest()
  50. request.projectID = projectID
  51. var query = Google_Datastore_V1_GqlQuery()
  52. query.queryString = "select *"
  53. request.gqlQuery = query
  54. print("\(request)")
  55. do {
  56. let result = try service.runquery(request)
  57. print("\(result)")
  58. } catch (let error) {
  59. print("ERROR: \(error)")
  60. }