main.swift 4.1 KB

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