main.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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:["profile",
  30. "https://www.googleapis.com/auth/contacts.readonly",
  31. "https://www.googleapis.com/auth/cloud-platform"])
  32. try tokenProvider.saveToken(TOKEN)
  33. }
  34. #else
  35. // On Linux, we can get a token if we are running in Google Cloud Shell
  36. // or in some other Google Cloud instance (GAE, GKE, GCE, etc).
  37. let tokenProvider = try GoogleTokenProvider()
  38. #endif
  39. gRPC.initialize()
  40. guard let authToken = tokenProvider.token?.AccessToken else {
  41. print("ERROR: No OAuth token is available.")
  42. exit(-1)
  43. }
  44. let projectID = "your-project-identifier"
  45. let certificateURL = URL(fileURLWithPath:"roots.pem")
  46. let certificates = try! String(contentsOf: certificateURL, encoding: .utf8)
  47. let service = Google_Datastore_V1_DatastoreService(address:"datastore.googleapis.com",
  48. certificates:certificates,
  49. host:nil)
  50. service.metadata = Metadata(["authorization":"Bearer " + authToken])
  51. var request = Google_Datastore_V1_RunQueryRequest()
  52. request.projectID = projectID
  53. var query = Google_Datastore_V1_GqlQuery()
  54. query.queryString = "select *"
  55. request.gqlQuery = query
  56. print("\(request)")
  57. do {
  58. let result = try service.runquery(request)
  59. print("\(result)")
  60. } catch (let error) {
  61. print("ERROR: \(error)")
  62. }