Using Resgate with Svelte

I am interested in using Resgate with Svelte (efficient, reactive, java script user interface) and I am looking for examples how others have integrated the two - this to speed up my learning as I am new to both Svelte and Resgate…

A concrete question: Can a resgate “model” possibly be used directly as a svelte “store” ?

Hi! I have never used Svelte, but from the looks of it, I would say: Yes.

After a quick look at their tutorials, and viewing some video on how to use Svelte with Firebase, it seems you just need to wrap ResClient models/collections to match a certain observable interface.

ResClient allows you to override the default ResModel and ResCollection classes used, so that you can have custom classes with custom methods. So, if you want to override all models/collections to let them have the subscribe method needed by Svelte stores, you can do this:

import ResClient, { ResModel, ResCollection } from 'resclient';

class SubscribableResModel extends ResModel {
	subscribe(cb) {
		this.on('change', cb);
		return () => this.off('change', cb);
	}
}

class SubscribableResCollection extends ResCollection {
	subscribe(cb) {
		this.on('add', cb);
		this.on('remove', cb);
		return () => {
			this.off('add', cb);
			this.off('remove', cb);
		};
	}
}

var client = new ResClient("ws://localhost:8080");

// Use our new custom classes for all models/collections, instead of the default.
// The wildcard (">") means it should be used for all resource IDs
client.registerModelType('>', (api, rid) => new SubscribableResModel(api, rid));
client.registerCollectionType('>', (api, rid) => new SubscribableResCollection(api, rid));

// Now we can use our new 'subscribe' method:
client.get('library.books').then(books => {
	books.subscribe(() => console.log("The list of books changed."));
});

Above code is untested!

Probably have to do something to provide Svelte with the the proper remove/add events as well.
Hmm, maybe I should try to make a working example.

Best regards,
Samuel

Hi, thanks for looking into this. That looks promising!