FirestoreDataConverter interface

withConverter() 使用的轉換器,將 AppModelType 類型的使用者物件轉換為 DbModelType 類型的 Firestore 資料。

使用轉換工具儲存及擷取 Firestore 中的物件時,您可以使用轉換工具指定一般類型引數。

在此情況下,「AppModel」是一種應用程式類別,用於將相關資訊和功能封裝在一起。舉例來說,這類類別可以具有以下屬性:含有複雜巢狀資料類型的屬性、用於記憶的屬性、Firestore 不支援的類型屬性 (例如 symbolbigint),以及執行複合作業的輔助函式。這類類別不適合且/或無法儲存至 Firestore 資料庫。相反地,這類類別的執行個體必須轉換為「普通的 JavaScript 物件」(POJO) 完全具備原始屬性,有可能嵌入其他 POJO 或 POJO 陣列中。在這個情況下,這種類型稱為「DbModel」且適合保存至 Firestore 的物件為方便起見,應用程式可以透過 DocumentReferenceQuery 等 Firestore 物件實作 FirestoreDataConverter,並註冊轉換器,以便在儲存至 Firestore 時自動將 AppModel 轉換為 DbModel,並從 Firestore 擷取時將 DbModel 轉換為 AppModel

簽名:

export declare interface FirestoreDataConverter<AppModelType, DbModelType extends DocumentData = DocumentData> 

方法

方法 說明
fromFirestore(快照) 由 Firestore SDK 呼叫,可將 Firestore 資料轉換為 AppModelType 類型的物件。您可以呼叫 snapshot.data() 來存取資料。一般而言,從 snapshot.data() 傳回的資料可以轉換為 DbModelType;不過,由於 Firestore 不會在資料庫強制執行結構定義,因此我們無法保證情況一定會如此。例如,從舊版的應用程式寫入,或是從未使用類型轉換器的其他用戶端寫入的資料,可能會以不同的屬性和/或屬性型別寫入資料。實作時,需要選擇要從不符合條件的資料妥善復原,還是擲回錯誤。
toFirestore(modelObject) 由 Firestore SDK 呼叫,目的是將類型為 AppModelType 的自訂模型物件轉換為 DbModelType 類型的純 JavaScript 物件 (適合直接寫入 Firestore 資料庫)。與 setDoc() 和 .WithFieldValue<T> 類型會擴充 T,允許將 deleteField() 等 FieldValue 做為屬性值使用。
toFirestore(modelObject, 選項) 由 Firestore SDK 呼叫,目的是將類型為 AppModelType 的自訂模型物件轉換為 DbModelType 類型的純 JavaScript 物件 (適合直接寫入 Firestore 資料庫)。可與 setDoc() 並搭配使用 merge:truemergeFieldsPartialWithFieldValue<T> 類型會擴充 Partial<T>,允許將 arrayUnion() 等 FieldValue 當做屬性值使用。還可以允許省略巢狀欄位,以支援巢狀 Partial

FirestoreDataConverter.fromFirestore()

由 Firestore SDK 呼叫,可將 Firestore 資料轉換為 AppModelType 類型的物件。你可以呼叫 snapshot.data() 來存取你的資料。

一般來說,從 snapshot.data() 傳回的資料可以轉換為 DbModelType;不過,由於 Firestore 不會在資料庫強制執行結構定義,因此我們無法保證情況一定會如此。例如,從舊版的應用程式寫入,或是從未使用類型轉換器的其他用戶端寫入的資料,可能會以不同的屬性和/或屬性型別寫入資料。實作時,需要選擇要從不符合條件的資料妥善復原,還是擲回錯誤。

簽名:

fromFirestore(snapshot: QueryDocumentSnapshot<DocumentData, DocumentData>): AppModelType;

參數

參數 類型 說明
快照 QueryDocumentSnapshot<DocumentDataDocumentData> 包含資料和中繼資料的 QueryDocumentSnapshot

傳回:

AppModelType

FirestoreDataConverter.toFirestore()

由 Firestore SDK 呼叫,可將 AppModelType 類型的自訂模型物件轉換為 DbModelType 類型的純 JavaScript 物件 (適合直接寫入 Firestore 資料庫)。可與 setDoc() 和 .

WithFieldValue<T> 類型會擴充 T,並允許 deleteField() 等 FieldValue 做為屬性值使用

簽名:

toFirestore(modelObject: WithFieldValue<AppModelType>): WithFieldValue<DbModelType>;

參數

參數 類型 說明
modelObject WithFieldValue<AppModelType>

傳回:

WithFieldValue<DbModelType>

FirestoreDataConverter.toFirestore()

由 Firestore SDK 呼叫,可將 AppModelType 類型的自訂模型物件轉換為 DbModelType 類型的純 JavaScript 物件 (適合直接寫入 Firestore 資料庫)。可與 setDoc() 以及 merge:truemergeFields 搭配使用。

PartialWithFieldValue<T> 類型會擴充 Partial<T>,允許 arrayUnion() 等 FieldValue 做為屬性值使用。還可以允許省略巢狀欄位,以支援巢狀 Partial

簽名:

toFirestore(modelObject: PartialWithFieldValue<AppModelType>, options: SetOptions): PartialWithFieldValue<DbModelType>;

參數

參數 類型 說明
modelObject PartialWithFieldValue<AppModelType>
選項 設定選項

傳回:

PartialWithFieldValue<DbModelType>

範例

簡易範例

const numberConverter = {
    toFirestore(value: WithFieldValue<number>) {
        return { value };
    },
    fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {
        return snapshot.data(options).value as number;
    }
};

async function simpleDemo(db: Firestore): Promise<void> {
    const documentRef = doc(db, 'values/value123').withConverter(numberConverter);

    // converters are used with `setDoc`, `addDoc`, and `getDoc`
    await setDoc(documentRef, 42);
    const snapshot1 = await getDoc(documentRef);
    assertEqual(snapshot1.data(), 42);

    // converters are not used when writing data with `updateDoc`
    await updateDoc(documentRef, { value: 999 });
    const snapshot2 = await getDoc(documentRef);
    assertEqual(snapshot2.data(), 999);
}

進階範例

// The Post class is a model that is used by our application.
// This class may have properties and methods that are specific
// to our application execution, which do not need to be persisted
// to Firestore.
class Post {
    constructor(
        readonly title: string,
        readonly author: string,
        readonly lastUpdatedMillis: number
    ) {}
    toString(): string {
        return `${this.title} by ${this.author}`;
    }
}

// The PostDbModel represents how we want our posts to be stored
// in Firestore. This DbModel has different properties (`ttl`,
// `aut`, and `lut`) from the Post class we use in our application.
interface PostDbModel {
    ttl: string;
    aut: { firstName: string; lastName: string };
    lut: Timestamp;
}

// The `PostConverter` implements `FirestoreDataConverter` and specifies
// how the Firestore SDK can convert `Post` objects to `PostDbModel`
// objects and vice versa.
class PostConverter implements FirestoreDataConverter<Post, PostDbModel> {
    toFirestore(post: WithFieldValue<Post>): WithFieldValue<PostDbModel> {
        return {
            ttl: post.title,
            aut: this._autFromAuthor(post.author),
            lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)
        };
    }

    fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {
        const data = snapshot.data(options) as PostDbModel;
        const author = `${data.aut.firstName} ${data.aut.lastName}`;
        return new Post(data.ttl, author, data.lut.toMillis());
    }

    _autFromAuthor(
        author: string | FieldValue
    ): { firstName: string; lastName: string } | FieldValue {
        if (typeof author !== 'string') {
            // `author` is a FieldValue, so just return it.
            return author;
        }
        const [firstName, lastName] = author.split(' ');
        return {firstName, lastName};
    }

    _lutFromLastUpdatedMillis(
        lastUpdatedMillis: number | FieldValue
    ): Timestamp | FieldValue {
        if (typeof lastUpdatedMillis !== 'number') {
            // `lastUpdatedMillis` must be a FieldValue, so just return it.
            return lastUpdatedMillis;
        }
        return Timestamp.fromMillis(lastUpdatedMillis);
    }
}

async function advancedDemo(db: Firestore): Promise<void> {
    // Create a `DocumentReference` with a `FirestoreDataConverter`.
    const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());

    // The `data` argument specified to `setDoc()` is type checked by the
    // TypeScript compiler to be compatible with `Post`. Since the `data`
    // argument is typed as `WithFieldValue<Post>` rather than just `Post`,
    // this allows properties of the `data` argument to also be special
    // Firestore values that perform server-side mutations, such as
    // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.
    await setDoc(documentRef, {
        title: 'My Life',
        author: 'Foo Bar',
        lastUpdatedMillis: serverTimestamp()
    });

    // The TypeScript compiler will fail to compile if the `data` argument to
    // `setDoc()` is _not_ compatible with `WithFieldValue<Post>`. This
    // type checking prevents the caller from specifying objects with incorrect
    // properties or property values.
    // @ts-expect-error "Argument of type { ttl: string; } is not assignable
    // to parameter of type WithFieldValue<Post>"
    await setDoc(documentRef, { ttl: 'The Title' });

    // When retrieving a document with `getDoc()` the `DocumentSnapshot`
    // object's `data()` method returns a `Post`, rather than a generic object,
    // which would have been returned if the `DocumentReference` did _not_ have a
    // `FirestoreDataConverter` attached to it.
    const snapshot1: DocumentSnapshot<Post> = await getDoc(documentRef);
    const post1: Post = snapshot1.data()!;
    if (post1) {
        assertEqual(post1.title, 'My Life');
        assertEqual(post1.author, 'Foo Bar');
    }

    // The `data` argument specified to `updateDoc()` is type checked by the
    // TypeScript compiler to be compatible with `PostDbModel`. Note that
    // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,
    // the `data` argument to `updateDoc()` must be compatible with
    // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed
    // as `WithFieldValue<PostDbModel>` rather than just `PostDbModel`, this
    // allows properties of the `data` argument to also be those special
    // Firestore values, like `arrayRemove()`, `deleteField()`, and
    // `serverTimestamp()`.
    await updateDoc(documentRef, {
        'aut.firstName': 'NewFirstName',
        lut: serverTimestamp()
    });

    // The TypeScript compiler will fail to compile if the `data` argument to
    // `updateDoc()` is _not_ compatible with `WithFieldValue<PostDbModel>`.
    // This type checking prevents the caller from specifying objects with
    // incorrect properties or property values.
    // @ts-expect-error "Argument of type { title: string; } is not assignable
    // to parameter of type WithFieldValue<PostDbModel>"
    await updateDoc(documentRef, { title: 'New Title' });
    const snapshot2: DocumentSnapshot<Post> = await getDoc(documentRef);
    const post2: Post = snapshot2.data()!;
    if (post2) {
        assertEqual(post2.title, 'My Life');
        assertEqual(post2.author, 'NewFirstName Bar');
    }
}