I defined a dart class A with some string variables and a list of objects of another class B. I don't find any method function in cloud_firestore module to set this custom object of class A, as a document to the collection, even though custom objects are supported in Firestore. Do I need to convert all the members(strings, lists etc) of class A to JSON format or any other solution available?
5
- By "a list of objects of another class B", I think you mean an array on A of B instances. A more natural representation of this in firestore is either a sub collection of A, or a another top-level collection containing B documents. Arranged that way, you can use the custom object converter in the SDK, but you'll need to setup the array yourself on the client.danh– danh2020-06-26 14:14:39 +00:00Commented Jun 26, 2020 at 14:14
- @danh I am developing a card game, where class A represents whole game state and class B represents the players (>5) state. So the document (game id) in collection (games) is updated whenever a player plays an action and all the players are listening to that document for changes. I am trying to keep all the game info in one document to reduce the number of reads from Firestore while game progresses. It requires minimum two reads with sub collections for each card action.Durga ga– Durga ga2020-06-27 06:24:22 +00:00Commented Jun 27, 2020 at 6:24
- Funny, I built a card game for my friends and me to use during social distancing, and I made the same decision about game state. The only way I know how to do it is to convert the related class (B) in the main class's (A's) converter.danh– danh2020-06-27 14:43:23 +00:00Commented Jun 27, 2020 at 14:43
- @danh Thanks. This is my first app. May I know which backend you are using to distribute the game state to every player on each action? Any sources to play or know the UI interfaces you have developed to play with your friends?Durga ga– Durga ga2020-06-30 06:56:32 +00:00Commented Jun 30, 2020 at 6:56
- I use firestore. Each player listens to the game state and updates it when they take an action. I use vue.js on the client, and the UI is a just a vertical list of players with their up cards, down cards, number of chips, etc. Hope that helps.danh– danh2020-06-30 13:28:39 +00:00Commented Jun 30, 2020 at 13:28
Add a comment |
2 Answers
In the event that it's inconvenient to create another collection of the related custom class, the only alternative is to build the related class instances yourself.
import Player from // player module class GameState { constructor(data) { this.players = data.players.map(p => new Player(p)) // ... } // flatten GameState into a generic JS map // build one of these on Player also asFBData() { const playerFBData = this.players.map(p => p.asFBData()) return { playerFBData, ...other_game_state_here } } } const gameStateConverter = { toFirestore: gameState => gameState.asFBData(), fromFirestore: (snapshot, options) => new GameState(snapshot.data(options)) }