3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Firestore: Reference型をJSONにするときの挙動を変える

Posted at

#前置き

例えば以下のようなデータをFunctionsでFirestoreのドキュメントusers/12345に入れたとする.

{
    "display_name": String,
    ...
    "userDetail": Reference
}

Functionsでこのデータを取ってきてJSONでクライアントに返すAPIを作る(error()とかsuccess()は別で作ってあるって言う体で...).

app.get("/users/:id", async (req, res, next) => {
    const users = await db.doc(`accounts/${req.params.id}`).get();
    if (!users.exists) {
        error(res, 404, "users_created", "You've not created first user.");
        return;
    }
    success(res, users.data());
    return;
});

するとこんな感じのデータが返ってくる

{
   "display_name": "Bony_Chops",
   ....
   "userDetail": {
       "_firestore": {
           "_settings": {
               "projectId": "nicha-nnct",
               "firebaseVersion": "9.5.0",
               "libName": "gccl",
               "libVersion": "4.9.4 fire/9.5.0",
               "ssl": false,
               ....
           }
           ....
       }
   ...
   }
}

Reference型がめっちゃでかい上ヤバそうな値を返してくる.これはまずい.

失敗例

Reference型の正体であるfirebase.firestore.DocumentReferenceクラスのtoJSONprototypeで上書きします(何故か補完でfirebase.default.firestore.DocumentReferenceだったのでそちらで...).とりあえず,そのReferenceが指すpathを返却するようにしてみます.

const firebase = require("firebase");

firebase.default.firestore.DocumentReference.prototype.toJSON = function () {
    return this.path;
}

でもさっきの結果は変わりませんでした.なんで???

結論

Firestoreへのアクセスをdb = admin.firestore();で行っていたのでadmin.firestore.DocumentReferenceを使うのが適切だったみたいです.

const admin = require('firebase-admin');

admin.firestore.DocumentReference.prototype.toJSON = function () {
    return this.path;
}

結果

{
    "display_name": "Bony_Chops",
    ...
    "userDetail": "users_detail/12345"
}

これでいい感じ.

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?