Let publication return modified/"fake"/non-database data, still queryable by client

71 Views Asked by At

A standard publication would look something like this:

Meteor.publish('suggestions', function(query){
    return MyDB.find({param: query});
}

and the results, once subscribed to, would then be accessible in the client by simple doing MyDB.find(...);.

However, how would I implement

(a) Some kind of pre-processing, meaning I add or remove certain properties to the queried documents on the server side, that should then still be queryable client-side?

(b) returning fake data, i.e. data following the database schema and still being queryable client-side, but not actually being present server side?

Example:

Meteor.publish('suggestions', function(query){
    //Stuff in database: [{prop1: 'first'}, {prop1: '2nd'}]
    if(query == 'something') { //Fake data
        return [{prop1: 'hello', prop2: 42}];
    } else {
        result = MyDB.find().fetch();
        result.forEach(function(element) {
            element.prop2 = random_number;
        }
        return result;
    }
}

So if I then subscribe to 'suggestions' on the client, I'd like to see the following:

//Subscribed with query 'something':
var arr = MyDB.find().fetch();
//arr equals [{prop1: 'hello', prop2: 42}]

Subscribed with another query
var arr = MyDB.find().fetch();
//arr equals [{prop1: 'first', prop2: random_number}, {prop1: '2nd', prop2: random_number}]

Basically, as said above, I want the database data to be modified a bit or completely before being sent to the client, but then the client should be able to query it as if it was coming directly from the database.

How would I go about doing this?

2

There are 2 best solutions below

1
rogeriojlle On

I believe that the answer given in

Meteor : how to publish custom JSON data?

I had a similar need and this answer helped me. You should manipulate the properties "added", "changed", "ready ()", etc. directly.

Or even evaluate whether it would be better to use "Meteor.call ()"

0
Flynn Hou On

I answered a similar question from How do you publish and subscribe to data that's not Mongo db?

I've put references and guides in that answer.

Note that the client side subscriber in that question was implemented in React.js, but I think the way to publish data on server side is almost the same.