Reputation: 293
I am implementing an offline mode for my iOS and web app that I am building with Meteor
.
So far the online mode works with an API, where I save and get all of my data using the HTTP
package.
Now I have started setting up a local db to save data when the app is offline using this solution: Link
So now, I can get my web app to use the API, and my mobile app to save data locally, but I can't find a nice way to have one piece of code that would work with both of them.
So here is my code:
1 - Where I call my method
Meteor.call('createDocument', myDataToSave, function( error, result)
{
console.log(error, result);
});
2 - My methods:
// First option
if( Meteor.isServer){
Meteor.methods({
createDocument: function( myDataToSave){
console.log('is server2');
return HTTP.post( API_URL, {
data: myDataToSave
});
}
});
}
// Second option
Meteor.methods({
createDocument: function(myDataToSave {
if (Meteor.isCordova) {
alert('is cordova');
return Documents.insert(myDataToSave);
} else if( Meteor.isServer){
console.log('is server');
return HTTP.post( API_URL, {
data: myDataToSave
});
} else {
console.log(Meteor);
}
}
});
So now what I don't understand is that when I am on my web browser testing the app locally, if I use the second option (comment out the first one), I have in my logs that Meteor.isClient
is true
, as the last else
is used.
If I use first option and comment out the second one, everything works fine, Meteor.isServer
is true
, so I can save my data to the API
So I guess my question is, how come in the same file, same way of calling it, Meteor
returns a different environment ? Does it come from declaring Metor.methods
inside or outside the Meteor.isServer
?
PS: I have found a solution to use both at the same time, which is to have two different methods, one for the server
and one for client
:
if (Meteor.isCordova) {
var method = 'createDocumentClient';
} else {
var method = 'createDocument';
}
Meteor.call(method, myDataToSave, function( error, result)
{
console.log(error, result);
});
But even though this solution seems to work, I still don't have a clue why this works and the first option doesn't, and would really appreciate if someone could help me understanding what is going on :)
Upvotes: 3
Views: 1619
Reputation: 20226
Assuming your code is at root or in /lib
, the method will run first on the client, then on the server. This is done for latency compensation and on the client is referred to as simulation. The .isServer
and .isClient
give you control over what environment you want your code to run in.
If you put methods in /client
then they will only run on the client and vice versa if you put them in /server
.
With the new ES6 imports you have specific control over what gets imported into each environment.
Upvotes: 1