I am using following MySQL package for database interaction in Meteor 2.7:
I am stuck at a point where I need to fetch data Synchronously.
I am running 2 separate queries where 2nd query’s result is dependent on first query’s result.
Here is my example script:
(This usersClass provides data to restivus api endpoint)
Meteor.startup(function () {
usersClass = {
getUsers: function (age){
var query = `SELECT * FROM users WHERE age = ${age}`;
connection.query(query, function (error, results, fields) {
if (error) throw error;
console.dir(results)
});
return results;
},
getHobbies: function (userId){
var query = `SELECT * FROM hobbies WHERE userId = ${userId}`;
connection.query(query, function (error, results, fields) {
if (error) throw error;
console.dir(results)
});
return results;
},
getStatistics: function (params){
var users = this.getUsers(params.age); // Some processing on users list data fetched from this.getUsers
var hobbies = this.getHobbies(params.userId); // Some processing on hobbies after fetching users data
}
};
});
As you can see hobbies data is dependent on the response result of users response.
I need all these queries to be synchronous where each query in sequence should wait for its process to be completed and then it should proceed for another query’s response.
I actually created an ORM for mysql using the above approach, which allows you to write CRUD calls to mysql tables using the same syntax as if you were using Mongodb in Meteor. This has the advantage of being easier to write the code, and you could switch databases relatively easily.
Restivus give you an easy way to provide endpoint for your mongo collections with little code.
The Restivus api functions can contain Meteor code, there should be no problem in using the above approach to do what you want.
var liveDb = new LiveMysql(Meteor.settings.mysql);
Meteor.publish('allPlayers', function(){
return liveDb.select(
`SELECT * FROM players ORDER BY score DESC`,
[ { table: 'players' } ]
);
});
Actually I don’t need reactive data from MySQL. I use Restivus plugin for throwing data on specific endpoints. That’s where I need to provide asynchronous data to a specific endpoint
import SimpleSchema from 'simpl-schema';
Meteor.methods({
'todos.updateText'({ todoId, newText }) {
new SimpleSchema({
todoId: { type: String },
newText: { type: String }
}).validate({ todoId, newText });
const todo = Todos.findOne(todoId);
if (!todo.editableBy(this.userId)) {
throw new Meteor.Error('todos.updateText.unauthorized',
'Cannot edit todos in a private list that is not yours');
}
Todos.update(todoId, {
$set: { text: newText }
});
}
});
When I started coding you got banned from forums for not reading the manual. Times have changed. Now I will be shadow banned or temporarily muted for telling you to read the manual. Millennials have it really different.