Reactive-Publish for Meteor 3: Revived and Ready for Composed and Derived Data Publishing

Published new beta version: nachocodoner:reactive-publish@1.1.0-beta.1

I’ve been working on the extension roadmap item, adding all the necessary changes so that, besides publishing any collection data reactively, you can now also publish any derived data you need.

To achieve this, I’ve revived and integrated the capabilities of the peerlibrary:subscription-data package directly into this library. With it, you can now publish derived data as shown below.

Infinite scrolling and counts

This example demonstrates how to publish a collection with a reactive total count while allowing the client to increase the number of published items without restarting the subscription.

Server:

import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { Mongo } from 'meteor/mongo';

export const Posts = new Mongo.Collection('posts');

Meteor.publish('posts.infiniteScroll', function () {
  // Reactive total count
  this.autorun(async () => {
    await this.setData('countAll', await Posts.find().countAsync());
  });

  // Reactive window of posts, adjustable by client
  this.autorun(async () => {
    const limit = Number(await this.data('limit')) || 10;
    check(limit, Number);
    return Posts.find({}, { limit, sort: { createdAt: -1 } });
  });
});

Client (Tracker):

import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { Posts } from '/imports/api/posts.js';

const sub = Meteor.subscribe('posts.infiniteScroll');

// Reactive total count
Tracker.autorun(async () => {
  console.log('Total posts:', await sub.data('countAll'));
});

// Adjust published window without restarting
sub.setData('limit', 20);

Other examples:

In short, you can now publish any data generated at publication runtime and its updates. This lets you take even more advantage of Meteor’s reactivity.

I open a testing and feedback period to fine-tune and address any issues we find. Current test coverage has been solid, showing the approach is already quite stable.

2 Likes