main.swift 5.5 KB

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