There are a few things you could do to improve the code:
That will only ever run once, as there are no reactive dependencies (.set()
of a ReactiveVar
does not establish a dependency). You could remove that section of code - it does no more than the instance.avatarsDownloaded = new ReactiveVar(false);
you declared above it. However, you probably don’t need that flag at all!
The canonical way of getting data from a Meteor Method and presenting it with a Template Helper is to put the method call in the onCreated
. That means something like this:
Template.serverchat.onCreated(function () {
// Steam Avatars
this.avatar = new ReactiveVar();
Meteor.call('steam.getAvatarURL', steamID, (error, result) => {
if (error) {
// handle error
} else {
this.avatar.set(result);
}
});
});
(Note that you do not seem to define steamId
anywhere - you just suddenly use it: its value will be undefined
at that point.)
Your helper is then simplified to something like this:
Template.serverchat.helpers({
steamAvatar() {
return Template.instance().avatar.get();
},
});
Reading between the lines, your Meteor method should be something like this (I’ve left out caching of data for simplicity):
Meteor.methods({
async 'steam.getAvatarURL'(SeamId) {
try {
const response = await steam.getUserSummary(SteamID);
return response.avatar.medium;
} catch (error) {
throw new Meteor.Error('E123', error.message);
}
},
});
I’m assuming your actual method sets up the steam
object appropriately for the method.
The easiest way to do this based on your caching code would be to check the database first:
const cachedData = SteamCache.findOne({ _id: SteamId, cachedTime: { $gt: timeNow - xDays } });
Which will only return the cached data if it exists and is recent (you’ll need to replace timeNow - Days
with sensible code). If you get nothing back, you will need to re-cache. However, as it stands, that is not a safe way to handle caching: if you add another property and reset the cachedTime
, it will affect all properties on the document. You may be better off attaching a timestamp to each property you add:
avatarURL: {
value: avatarURL,
cachedTime: new Date()
},
and changing the query appropriately.