ServerTimestamp.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright 2020 Google LLC
  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. #if SWIFT_PACKAGE
  17. @_exported import FirebaseDatabaseInternal
  18. #endif // SWIFT_PACKAGE
  19. /// A property wrapper that marks an `Optional<Date>` field to be
  20. /// populated with a server timestamp. If a `Codable` object being written
  21. /// contains a `nil` for an `@ServerTimestamp`-annotated field, it will be
  22. /// replaced with `ServerValue.timestamp()` as it is sent.
  23. ///
  24. /// Example:
  25. /// ```
  26. /// struct CustomModel {
  27. /// @ServerTimestamp var ts: Date?
  28. /// }
  29. /// ```
  30. ///
  31. /// Then writing `CustomModel(ts: nil)` will tell server to fill `ts` with
  32. /// current timestamp.
  33. @propertyWrapper
  34. public struct ServerTimestamp: Codable, Equatable, Hashable {
  35. var value: Date?
  36. public init(wrappedValue value: Date?) {
  37. self.value = value
  38. }
  39. public var wrappedValue: Date? {
  40. get { value }
  41. set { value = newValue }
  42. }
  43. // MARK: Codable
  44. public init(from decoder: Decoder) throws {
  45. let container = try decoder.singleValueContainer()
  46. if container.decodeNil() {
  47. value = nil
  48. } else {
  49. let msecs = try container.decode(Int.self)
  50. value = Date(timeIntervalSince1970: TimeInterval(msecs) / 1000)
  51. }
  52. }
  53. public func encode(to encoder: Encoder) throws {
  54. var container = encoder.singleValueContainer()
  55. if let value {
  56. let interval = value.timeIntervalSince1970
  57. try container.encode(Int(interval * 1000))
  58. } else {
  59. let dictionary = ServerValue.timestamp() as! [String: String]
  60. try container.encode(dictionary)
  61. }
  62. }
  63. }