main.swift 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. import Commander
  20. let projectID = "your-project-identifier"
  21. let scopes = ["https://www.googleapis.com/auth/datastore"]
  22. struct Thing : Codable {
  23. var name: String
  24. var number: Int
  25. }
  26. // Convert Encodable objects to dictionaries of property-value pairs.
  27. class PropertiesEncoder {
  28. static func encode<T : Encodable>(_ value : T) throws -> [String:Any]? {
  29. let plist = try PropertyListEncoder().encode(value)
  30. let properties = try PropertyListSerialization.propertyList(from:plist, options:[], format:nil)
  31. return properties as? [String:Any]
  32. }
  33. }
  34. // Create Decodable objects from dictionaries of property-value pairs.
  35. class PropertiesDecoder {
  36. static func decode<T: Decodable>(_ type: T.Type, from: [String:Any]) throws -> T {
  37. let plist = try PropertyListSerialization.data(fromPropertyList: from,
  38. format: .binary, options:0)
  39. return try PropertyListDecoder().decode(type, from: plist)
  40. }
  41. }
  42. func prepareService() throws -> Google_Datastore_V1_DatastoreService? {
  43. // Get an OAuth token
  44. var authToken : String!
  45. if let provider = DefaultTokenProvider(scopes:scopes) {
  46. let sem = DispatchSemaphore(value: 0)
  47. try provider.withToken() {(token, error) -> Void in
  48. if let token = token {
  49. authToken = token.AccessToken
  50. }
  51. sem.signal()
  52. }
  53. sem.wait()
  54. }
  55. if authToken == nil {
  56. print("ERROR: No OAuth token is available. Did you set GOOGLE_APPLICATION_CREDENTIALS?")
  57. exit(-1)
  58. }
  59. // Initialize gRPC service
  60. gRPC.initialize()
  61. let certificateURL = URL(fileURLWithPath:"/roots.pem")
  62. let certificates = try! String(contentsOf: certificateURL, encoding: .utf8)
  63. let service = Google_Datastore_V1_DatastoreService(address:"datastore.googleapis.com",
  64. certificates:certificates,
  65. host:nil)
  66. service.metadata = Metadata(["authorization":"Bearer " + authToken])
  67. return service
  68. }
  69. func performList(service: Google_Datastore_V1_DatastoreService) throws {
  70. var request = Google_Datastore_V1_RunQueryRequest()
  71. request.projectID = projectID
  72. var query = Google_Datastore_V1_GqlQuery()
  73. query.queryString = "select * from Thing"
  74. request.gqlQuery = query
  75. let result = try service.runquery(request)
  76. var entities : [Int64 : Thing] = [:]
  77. for entityResult in result.batch.entityResults {
  78. var properties : [String:Any] = [:]
  79. for property in entityResult.entity.properties {
  80. let key = property.key
  81. switch property.value.valueType! {
  82. case .integerValue(let v):
  83. properties[key] = v
  84. case .stringValue(let v):
  85. properties[key] = v
  86. default:
  87. print("?")
  88. }
  89. }
  90. let entity = try PropertiesDecoder.decode(Thing.self, from:properties)
  91. entities[entityResult.entity.key.path[0].id] = entity
  92. }
  93. print("\(entities)")
  94. }
  95. func performInsert(service: Google_Datastore_V1_DatastoreService,
  96. number: Int) throws {
  97. var request = Google_Datastore_V1_CommitRequest()
  98. request.projectID = projectID
  99. request.mode = .nonTransactional
  100. var pathElement = Google_Datastore_V1_Key.PathElement()
  101. pathElement.kind = "Thing"
  102. var key = Google_Datastore_V1_Key()
  103. key.path = [pathElement]
  104. var entity = Google_Datastore_V1_Entity()
  105. entity.key = key
  106. let thing = Thing(name:"Thing", number:number)
  107. let properties = try PropertiesEncoder.encode(thing)!
  108. for (k,v) in properties {
  109. var value = Google_Datastore_V1_Value()
  110. switch v {
  111. case let v as String:
  112. value.stringValue = v
  113. case let v as Int:
  114. value.integerValue = Int64(v)
  115. default:
  116. break
  117. }
  118. entity.properties[k] = value
  119. }
  120. var mutation = Google_Datastore_V1_Mutation()
  121. mutation.insert = entity
  122. request.mutations.append(mutation)
  123. let result = try service.commit(request)
  124. for mutationResult in result.mutationResults {
  125. print("\(mutationResult)")
  126. }
  127. }
  128. func performDelete(service: Google_Datastore_V1_DatastoreService,
  129. kind: String,
  130. id: Int64) throws {
  131. var request = Google_Datastore_V1_CommitRequest()
  132. request.projectID = projectID
  133. request.mode = .nonTransactional
  134. var pathElement = Google_Datastore_V1_Key.PathElement()
  135. pathElement.kind = kind
  136. pathElement.id = id
  137. var key = Google_Datastore_V1_Key()
  138. key.path = [pathElement]
  139. var mutation = Google_Datastore_V1_Mutation()
  140. mutation.delete = key
  141. request.mutations.append(mutation)
  142. let result = try service.commit(request)
  143. for mutationResult in result.mutationResults {
  144. print("\(mutationResult)")
  145. }
  146. }
  147. Group {
  148. $0.command("insert") { (number:Int) in
  149. if let service = try prepareService() {
  150. try performInsert(service:service, number:number)
  151. }
  152. }
  153. $0.command("delete") { (id:Int) in
  154. if let service = try prepareService() {
  155. try performDelete(service:service, kind:"Thing", id:Int64(id))
  156. }
  157. }
  158. $0.command("list") {
  159. if let service = try prepareService() {
  160. try performList(service:service)
  161. }
  162. }
  163. }.run()