ServerTimestamp.swift 2.0 KB

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