main.swift 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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 service = Google_Datastore_V1_DatastoreService(address:"datastore.googleapis.com")
  62. service.metadata = Metadata(["authorization":"Bearer " + authToken])
  63. return service
  64. }
  65. func performList(service: Google_Datastore_V1_DatastoreService) throws {
  66. var request = Google_Datastore_V1_RunQueryRequest()
  67. request.projectID = projectID
  68. var query = Google_Datastore_V1_GqlQuery()
  69. query.queryString = "select * from Thing"
  70. request.gqlQuery = query
  71. let result = try service.runquery(request)
  72. var entities : [Int64 : Thing] = [:]
  73. for entityResult in result.batch.entityResults {
  74. var properties : [String:Any] = [:]
  75. for property in entityResult.entity.properties {
  76. let key = property.key
  77. switch property.value.valueType! {
  78. case .integerValue(let v):
  79. properties[key] = v
  80. case .stringValue(let v):
  81. properties[key] = v
  82. default:
  83. print("?")
  84. }
  85. }
  86. let entity = try PropertiesDecoder.decode(Thing.self, from:properties)
  87. entities[entityResult.entity.key.path[0].id] = entity
  88. }
  89. print("\(entities)")
  90. }
  91. func performInsert(service: Google_Datastore_V1_DatastoreService,
  92. number: Int) throws {
  93. var request = Google_Datastore_V1_CommitRequest()
  94. request.projectID = projectID
  95. request.mode = .nonTransactional
  96. var pathElement = Google_Datastore_V1_Key.PathElement()
  97. pathElement.kind = "Thing"
  98. var key = Google_Datastore_V1_Key()
  99. key.path = [pathElement]
  100. var entity = Google_Datastore_V1_Entity()
  101. entity.key = key
  102. let thing = Thing(name:"Thing", number:number)
  103. let properties = try PropertiesEncoder.encode(thing)!
  104. for (k,v) in properties {
  105. var value = Google_Datastore_V1_Value()
  106. switch v {
  107. case let v as String:
  108. value.stringValue = v
  109. case let v as Int:
  110. value.integerValue = Int64(v)
  111. default:
  112. break
  113. }
  114. entity.properties[k] = value
  115. }
  116. var mutation = Google_Datastore_V1_Mutation()
  117. mutation.insert = entity
  118. request.mutations.append(mutation)
  119. let result = try service.commit(request)
  120. for mutationResult in result.mutationResults {
  121. print("\(mutationResult)")
  122. }
  123. }
  124. func performDelete(service: Google_Datastore_V1_DatastoreService,
  125. kind: String,
  126. id: Int64) throws {
  127. var request = Google_Datastore_V1_CommitRequest()
  128. request.projectID = projectID
  129. request.mode = .nonTransactional
  130. var pathElement = Google_Datastore_V1_Key.PathElement()
  131. pathElement.kind = kind
  132. pathElement.id = id
  133. var key = Google_Datastore_V1_Key()
  134. key.path = [pathElement]
  135. var mutation = Google_Datastore_V1_Mutation()
  136. mutation.delete = key
  137. request.mutations.append(mutation)
  138. let result = try service.commit(request)
  139. for mutationResult in result.mutationResults {
  140. print("\(mutationResult)")
  141. }
  142. }
  143. Group {
  144. $0.command("insert") { (number:Int) in
  145. if let service = try prepareService() {
  146. try performInsert(service:service, number:number)
  147. }
  148. }
  149. $0.command("delete") { (id:Int) in
  150. if let service = try prepareService() {
  151. try performDelete(service:service, kind:"Thing", id:Int64(id))
  152. }
  153. }
  154. $0.command("list") {
  155. if let service = try prepareService() {
  156. try performList(service:service)
  157. }
  158. }
  159. }.run()