main.swift 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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 projectID = "your-project-identifier"
  20. let scopes = ["https://www.googleapis.com/auth/datastore"]
  21. struct Thing : Codable {
  22. var name: String
  23. var number: Int
  24. }
  25. class PropertiesEncoder {
  26. static func encode<T : Encodable>(_ value : T) throws -> [String:Any]? {
  27. let plist = try PropertyListEncoder().encode(value)
  28. let properties = try PropertyListSerialization.propertyList(from:plist, options:[], format:nil)
  29. return properties as? [String:Any]
  30. }
  31. }
  32. class PropertiesDecoder {
  33. static func decode<T: Decodable>(_ type: T.Type, from: [String:Any]) throws -> T {
  34. let plist = try PropertyListSerialization.data(fromPropertyList: from,
  35. format: .binary, options:0)
  36. return try PropertyListDecoder().decode(type, from: plist)
  37. }
  38. }
  39. func runSelectQuery(service: Google_Datastore_V1_DatastoreService) throws {
  40. var request = Google_Datastore_V1_RunQueryRequest()
  41. request.projectID = projectID
  42. var query = Google_Datastore_V1_GqlQuery()
  43. query.queryString = "select *"
  44. request.gqlQuery = query
  45. print("\(request)")
  46. let result = try service.runquery(request)
  47. print("\(result)")
  48. }
  49. func runInsert(service: Google_Datastore_V1_DatastoreService) throws {
  50. var request = Google_Datastore_V1_CommitRequest()
  51. request.projectID = projectID
  52. request.mode = .nonTransactional
  53. var pathElement = Google_Datastore_V1_Key.PathElement()
  54. pathElement.kind = "Thing"
  55. var key = Google_Datastore_V1_Key()
  56. key.path = [pathElement]
  57. var entity = Google_Datastore_V1_Entity()
  58. entity.key = key
  59. let thing = Thing(name:"Thing", number:1)
  60. let properties = try PropertiesEncoder.encode(thing)!
  61. for (k,v) in properties {
  62. var value = Google_Datastore_V1_Value()
  63. switch v {
  64. case let v as String:
  65. value.stringValue = v
  66. case let v as Int:
  67. value.integerValue = Int64(v)
  68. default:
  69. break
  70. }
  71. entity.properties[k] = value
  72. }
  73. var mutation = Google_Datastore_V1_Mutation()
  74. mutation.insert = entity
  75. request.mutations.append(mutation)
  76. let result = try service.commit(request)
  77. print("\(result)")
  78. }
  79. func main() throws {
  80. // Get an OAuth token
  81. var authToken : String!
  82. if let provider = DefaultTokenProvider(scopes:scopes) {
  83. let sem = DispatchSemaphore(value: 0)
  84. try provider.withToken() {(token, error) -> Void in
  85. if let token = token {
  86. authToken = token.AccessToken
  87. }
  88. sem.signal()
  89. }
  90. sem.wait()
  91. }
  92. if authToken == nil {
  93. print("ERROR: No OAuth token is available. Did you set GOOGLE_APPLICATION_CREDENTIALS?")
  94. exit(-1)
  95. }
  96. // Initialize gRPC service
  97. gRPC.initialize()
  98. let certificateURL = URL(fileURLWithPath:"/roots.pem")
  99. let certificates = try! String(contentsOf: certificateURL, encoding: .utf8)
  100. let service = Google_Datastore_V1_DatastoreService(address:"datastore.googleapis.com",
  101. certificates:certificates,
  102. host:nil)
  103. service.metadata = Metadata(["authorization":"Bearer " + authToken])
  104. // Run some queries
  105. try runInsert(service:service)
  106. try runSelectQuery(service:service)
  107. }
  108. do {
  109. try main()
  110. } catch (let error) {
  111. print("ERROR: \(error)")
  112. }