JSONCodeGenerator.swift 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. /*
  2. * Copyright 2025, 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 GRPCCodeGen
  18. struct JSONCodeGenerator {
  19. private static let currentYear: Int = {
  20. let now = Date()
  21. let year = Calendar.current.component(.year, from: Date())
  22. return year
  23. }()
  24. private static let header = """
  25. /*
  26. * Copyright \(Self.currentYear), gRPC Authors All rights reserved.
  27. *
  28. * Licensed under the Apache License, Version 2.0 (the "License");
  29. * you may not use this file except in compliance with the License.
  30. * You may obtain a copy of the License at
  31. *
  32. * http://www.apache.org/licenses/LICENSE-2.0
  33. *
  34. * Unless required by applicable law or agreed to in writing, software
  35. * distributed under the License is distributed on an "AS IS" BASIS,
  36. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37. * See the License for the specific language governing permissions and
  38. * limitations under the License.
  39. */
  40. """
  41. private static let jsonSerializers: String = """
  42. fileprivate struct JSONSerializer<Message: Codable>: MessageSerializer {
  43. fileprivate func serialize<Bytes: GRPCContiguousBytes>(
  44. _ message: Message
  45. ) throws -> Bytes {
  46. do {
  47. let jsonEncoder = JSONEncoder()
  48. let data = try jsonEncoder.encode(message)
  49. return Bytes(data)
  50. } catch {
  51. throw RPCError(
  52. code: .internalError,
  53. message: "Can't serialize message to JSON.",
  54. cause: error
  55. )
  56. }
  57. }
  58. }
  59. fileprivate struct JSONDeserializer<Message: Codable>: MessageDeserializer {
  60. fileprivate func deserialize<Bytes: GRPCContiguousBytes>(
  61. _ serializedMessageBytes: Bytes
  62. ) throws -> Message {
  63. do {
  64. let jsonDecoder = JSONDecoder()
  65. let data = serializedMessageBytes.withUnsafeBytes { Data($0) }
  66. return try jsonDecoder.decode(Message.self, from: data)
  67. } catch {
  68. throw RPCError(
  69. code: .internalError,
  70. message: "Can't deserialize message from JSON.",
  71. cause: error
  72. )
  73. }
  74. }
  75. }
  76. """
  77. func generate(request: JSONCodeGeneratorRequest) throws -> SourceFile {
  78. let generator = CodeGenerator(config: CodeGenerator.Config(request.config))
  79. let codeGenRequest = CodeGenerationRequest(
  80. fileName: request.service.name + ".swift",
  81. leadingTrivia: Self.header,
  82. dependencies: [
  83. Dependency(
  84. item: Dependency.Item(kind: .struct, name: "Data"),
  85. module: "Foundation",
  86. accessLevel: .internal
  87. ),
  88. Dependency(
  89. item: Dependency.Item(kind: .class, name: "JSONEncoder"),
  90. module: "Foundation",
  91. accessLevel: .internal
  92. ),
  93. Dependency(
  94. item: Dependency.Item(kind: .class, name: "JSONDecoder"),
  95. module: "Foundation",
  96. accessLevel: .internal
  97. ),
  98. ],
  99. services: [ServiceDescriptor(request.service)],
  100. makeSerializerCodeSnippet: { type in "JSONSerializer<\(type)>()" },
  101. makeDeserializerCodeSnippet: { type in "JSONDeserializer<\(type)>()" }
  102. )
  103. var sourceFile = try generator.generate(codeGenRequest)
  104. // Insert a fileprivate serializer/deserializer for JSON at the bottom of each file.
  105. sourceFile.contents += "\n\n"
  106. sourceFile.contents += Self.jsonSerializers
  107. return sourceFile
  108. }
  109. }