IjzerenHein / firestorter

Use Google Firestore in React with zero effort, using MobX 🤘
http://firestorter.com
MIT License
378 stars 50 forks source link

Allow to have different types of Documents in Collection #43

Closed yatsyk closed 5 years ago

yatsyk commented 5 years ago

Sometimes it is useful to have different types of documents in collection. Now we are passing DocumentClass to Collection constructor. I see two options to implement this type of API. One is to pass callback that returns correct class of Document object according to snapshot data.

class Pet extends Document {...}
class Cat extends Pet {...}
class Dog extends Pet {...}

const pets = Collection('pets', {getDocumentClass: docSnapshot => {/*returns correct class*/}})

The other option is to pass document factory method that creates objects.

const pets = Collection('pets', {createDocument: docSnapshot => {/*creates document by snapshot*/}})

Second approach is better as we could pass any additional data to constructor, but in this case we should also provide some callback that shows can we reuse object of current document class or should it be recreated with new class.

IjzerenHein commented 5 years ago

Hi Andrey, thanks for the suggestion, I really like this idea. I had come up with it myself a while back, but never found a use case for it, so I never implemented it. I like the createDocument naming the best. Also, I agree with passing in DocumentSnapshot to the factory function. I will include this improvement in the next big release, which includes proper TypeScript support and a "pure" mobx mode.

Cheers, and thanks for the suggestion.

IjzerenHein commented 5 years ago

Hi, this feature is now officially supported. To create custom documents, you can now use the createDocument option in the constructor of the Collection.

Example

const col = new Collection('settings', {
  createDocument: (source, options) => {
    if (options.snapshot.data().type === 'user') {
      return new UserSetting(source, options);
    } else {
      return new Setting(source, options);
    }
  }
});

Cheers!

IjzerenHein commented 5 years ago

Just released this feature in: https://github.com/IjzerenHein/firestorter/releases/tag/v1.1.0

yatsyk commented 5 years ago

Thank you!