route(path, callback) {
this.router.get('/' + path, async (ctx, next) => {
ctx.status = 200;
ctx.body = 'GET ' + '/' + path + ' is online!';
if (callback && typeof callback === 'function') await callback(ctx, next);
});
}
this.route(name, async (ctx) => {
await MongoModel.find({}, async (err, objects) => {
ctx.status = 200;
ctx.body = objects;
if (err)
ctx.body = 'Mongo Error';
})
});
Any idea of why this code shows randomly either the result of:
ctx.body = 'GET ' + '/' + path + ' is online!';
either the result of:
ctx.body = objects;
when objects is ALWAYS set? (checked with console log).
Honestly, I don't get it.
Sorry, there's insufficient information to be able to debug this. Common mistakes are having conflicting route paths or not calling and return/await next(). I recommend you to try stepping through your code find a way to consistently recreate diff.
I'm going to close this due to inactivity. But if you come back with the same issue and more information regarding your problem feel free to reopen!
Solved the issue.
First, I'll apologize for a couple of things:
Then, here is the correct way to handle the need of a callback inside a routed path. Promise usage was needed.
function route(path, callback) {
this.router.get('/' + path, async (ctx, next) => {
ctx.status = 200;
if (callback && typeof callback === 'function')
ctx.body = callback(ctx, next);
});
}
async function myCallback(ctx, next) {
return new Promise(resolve => {
resolve('This will be printed in ctx.body';
});
}
And then you just call:
route('mypath', myCallback);
Thanks anyway, @fl0w