Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] - Referenceable Object Swift PropertyWrapper - @FirestoreObjectReference #11330

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions Firestore/Swift/Source/Common/FirestoreLogger.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import Foundation
import OSLog

/// Base FirestoreLogger class
/// Logging categories can be created by extending FirestoreLogger and defining a static FirestoreLogger var with your category
///
/// ```
/// extension FirestoreLogger {
/// static var myCategory = FirestoreLogger(category: "myCategory")
/// }
/// ```
///
/// To use your extension, call
/// ```
/// FirestoreLogger.myCategory.log(msg, vars)
/// ```
/// See ReferenceableObject.swift for the FirestoreLogger extension for an example

@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
class FirestoreLogger: OSLog {
private let firestoreSubsystem = "com.google.firebase.firestore"

init(category: String) {
super.init(subsystem: firestoreSubsystem, category: category)
}

func debug(_ message: StaticString, _ args: CVarArg...) {
os_log(message, log: self, type: .debug, args)
}

func info(_ message: StaticString, _ args: CVarArg...) {
os_log(message, log: self, type: .info, args)
}

func log(_ message: StaticString, _ args: CVarArg...) {
os_log(message, log: self, type: .default, args)
}

func error(_ message: StaticString, _ args: CVarArg) {
os_log(message, log: self, type: .error, args)
}

func fault(_ message: StaticString, _ args: CVarArg) {
os_log(message, log: self, type: .fault, args)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import FirebaseFirestore

/// Property wrapper @FirestoreObjectReference,
/// Indicates that the specified property value should be stored by reference instead of by value
///
/// When loading a parent object, any references are not loaded by default and can be loaded on demand
/// using the projected value of the wrapper.
///
/// Structs that can be stored as a reference must implement the `ReferenceableObject` protocol
///
/// Variables that are annotated with the propertyWrapper should be marked as `Optional` since they can be nil when not loaded or set
///
/// Example:
/// We have three structs representing a simplified UserProfile model -
/// `UserProfile`
/// `Employer` - an employer who the `UserProfile` works for
/// `WorkLocation` - representing a generic location. This can be used to represent a generic location
///
/// Since multiple Users can work for an Employer, it makes sense to have only one instance of an Employer that is referred to
/// by multiple Users. Similarly multiple users can be in a WorkLocation. Additionally, an Employer can also be located
/// in a WorkLocation (e.g. headquarters of an Employer). We can mark WorkLocation and Employer as a ReferenceableObjects.
///
///
/// ```
/// struct UserProfile: ReferenceableObject {
/// var username: String
///
/// @FirestoreObjectReference
/// var employer: Employer?
///
/// @FirestoreObjectReference
/// var workLocation: WorkLocation?
///
/// }
///
/// struct Employer: ReferenceableObject {
/// var name: String
///
/// @FirestoreObjectReference
/// var headquarters: WorkLocation?
/// }
///
/// struct WorkLocation: ReferenceableObject {
/// var locationName: String
/// var moreInfo: String
///
/// }
///
/// var userProfile = ...
///
/// // use projected value to load referenced employer
/// try await userProfile.$employer?.loadReferencedObject()
///
/// // use projected value to load referenced workLocation
/// try await prof.$workLocation?.loadReferencedObject()
///
///
///
/// ```
///
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
@propertyWrapper
public struct FirestoreObjectReference<T> where T: ReferenceableObject {
private var objectReference: ObjectReference<T>?

public init(wrappedValue initialValue: T?) {
updateInitialValue(initialValue: initialValue)
}

private mutating func updateInitialValue(initialValue: T?) {
if let initialValue {
let objId = initialValue.id ?? {
let docRef = Firestore.firestore().collection(T.parentCollection()).document()
return docRef.documentID
}()

objectReference = ObjectReference(
objectId: objId,
collection: T.parentCollection(),
referencedObject: initialValue
)
}
}

public var wrappedValue: T? {
get {
return objectReference?.referencedObject
}

set {
if objectReference != nil {
objectReference?.referencedObject = newValue
} else {
updateInitialValue(initialValue: newValue)
}
}
}

public var projectedValue: ObjectReference<T>? {
get {
return objectReference
}
set {
objectReference = newValue
}
}
}

@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension FirestoreObjectReference: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let objRef = try container.decode(ObjectReference<T>.self)
objectReference = objRef
}

public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if let objectReference {
try container.encode(objectReference)

if let value = objectReference.referencedObject {
Task {
try await ReferenceableObjectManager.instance.save(object: value)
}
}

} else {
try container.encodeNil()
}
}
}
119 changes: 119 additions & 0 deletions Firestore/Swift/Source/ReferenceableObject/ReferenceableObject.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import FirebaseFirestore

import CryptoKit
import OSLog

/// A protocol that denotes an object that can be "stored by reference" in Firestore.
/// Structs that implement this and are contained in other Structs, are stored as a reference
/// instead of stored inline if the FirestoreObjectReference propertyWrapper is used to annotate them.
///
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public protocol ReferenceableObject: Codable, Identifiable, Hashable, Equatable {
// The Firestore collection where objects of this type are stored.
// If no value is specified, it defaults to type name of the object
static func parentCollection() -> String

var id: String? { get set }

var path: String? { get }

static func objectPath(objectId: String) -> String
}

// default implementations
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public extension ReferenceableObject {
static func parentCollection() -> String {
let t = type(of: self)
return String(describing: t)
}

func hash(into hasher: inout Hasher) {
hasher.combine(path)
}

static func == (lhs: Self, rhs: Self) -> Bool {
if let lpath = lhs.path,
let rpath = rhs.path {
return lpath == rpath
} else {
return false
}
}

var path: String? {
guard let id else {
return nil
}

return Self.objectPath(objectId: id)
}

// Helper function that creates a path for the object
static func objectPath(objectId: String) -> String {
let collection = Self.parentCollection()
if collection.hasSuffix("/") {
return collection + objectId
} else {
return collection + "/" + objectId
}
}
}

// MARK: Contained Object Reference

/// Struct used to store a reference to a ReferenceableObject. When a container struct is
/// encoded, any FirestoreObjectReference property wrappers are encoded as ObjectReference objects and the referenced
/// objects are stored (if needed) in their intended location instead of inline.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"inline" - I haven't seen this terminology being used in the context of Firestore. Check with the Firestore team what their preferred way of describing this is.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't figure out a better way of saying this. Let me see some docs too.

///
/// For example:
/// When storing UserProfile, which contains an Employer referenceable object, Employer object is stored
/// in the Employer collection and a reference to Employer object is stored within the UserProfile encoded document.
///
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public struct ObjectReference<T: ReferenceableObject>: Codable {
/// documentId of referenced object
public var objectId: String

/// collection where the referenced object is stored
public var collection: String

/// The referenced object. By default, it is not loaded. Apps can load this calling the loadReferencedObject() function.
public var referencedObject: T?

enum CodingKeys: String, CodingKey {
case objectId
case collection
}

/// Loads the referenced object from the db and assigns it to the referencedObject property
public mutating func loadReferencedObject() async throws {
let obj: T? = try await ReferenceableObjectManager.instance.getObject(objectId: objectId)
referencedObject = obj
}
}

// MARK: Logger

@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension FirestoreLogger {
static var objectReference = FirestoreLogger(
category: "objectReference"
)
}
Loading
Loading