koa doesn't render a page (404) after mongodb request - mongodb

I am trying to render a page with something I load from MongoDB:
router.get('/messages', async (ctx, next) => {
await MessageModel.find()
.then((result:any) => {
ctx.render('index', {
title: 'Messages',
messages: result
})
});
});
I got 404 message after I go to /messages but it works fine when I render it without approaching to DB:
router.get('/messages', async ctx => {
await ctx.render('index', {
title: 'Messages'
})
});
Sorry for my 'noob' question, I am just making my first steps into coding. Thanks for help.

You should await for models result or consume them with .then(), not both at the same time. Try this:
router.get('/messages', async (ctx, next) => {
let result = await MessageModel.find()
await ctx.render('index', {
title: 'Messages',
messages: result
})
})

Related

Can I dispatch another rtk query from queryFn and await it before continuing?

Essentially I want to await a bunch of queries before resolving a queryFn. An example of this is as follows:
What I know I can do currently
I'm aware I can do the following however this looks like it could get messy for more complex examples.
queryFn: async (
{ emailAddress, password },
{ dispatch },
_,
baseQuery,
) => {
await cognito.login(emailAddress, password)
const { data, error } = await baseQuery({
url: `me`,
method: 'GET',
})
await dispatch(
userService.util.updateQueryData('getUser', {}, (draft) => {
draft = data
}),
)
return { data, error }
},
What I'd like to do
Doing the following would mean I don't have to updateQueryData and duplicate endpoint URLs. Also it would mean that I can use errors from other queries to determine if the whole process went as planned.
queryFn: async (
{ emailAddress, password },
{ dispatch },
) => {
await cognito.login(emailAddress, password)
const {data,error} = dispatch(userService.endpoints.getUser.initiate({ }, { forceRefetch })) // await this
It looks like this was more simple than I'd thought
login: builder.mutation<{}, Req['login']>({
queryFn: async ({ emailAddress, password }, { dispatch }) => {
await Promise.resolve() // do stuff like hit cognito, an api ect
return dispatch(
userService.endpoints.getUser.initiate({}, { forceRefetch: true }),
)
},
}),
getUser: builder.query<Res['user'], Req['getUser']>({
queryFn: async (args, _, _2, baseQuery) => {
throw 'Hi i am an error'
},
}),
// this becomes {message:"Hi I am an error"} proving it's awaited
const [login, { error, data }] = useLoginMutation({})

Redirecting url with Puppeteer by changing url

I am trying to get change my request url and see the new url in the response
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', interceptedRequest => {
if (interceptedRequest.url().includes('some-string')) {
interceptedRequest.respond({
status: 302,
headers: {
url: 'www.new.url.com'
},
})
}
interceptedRequest.continue()
});
page.on('response', response => {
console.log(response.url())
})
await page.goto('www.orginal.url.com')
// some code omitted
})();
In the interceptedRequest.respond method I'm trying to update the value of the url. Originally I was trying:
interceptedRequest.continue({url: 'www.new.url.com'})
but that way is not long supported in the current version of Puppeteer.
I was expecting to get www.new.url.com in the response, but I actually get the orignial url with www.new.url.com appended to the end.
Thanks in advance for any help.
It helped me. You need to change url to location
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', interceptedRequest => {
if (interceptedRequest.url().includes('some-string')) {
interceptedRequest.respond({
status: 302,
headers: {
location: 'www.new.url.com'
},
})
}
});
page.on('response', response => {
console.log(response.url())
})
await page.goto('www.orginal.url.com')
// some code omitted
})();

HTTP .get() method does not respond with anything

I am trying to use Express + MongoDB building React app.
I was able to post some documents to MongoDB and delete them. Currently, I'm trying to figure out how to get them using HTTP .get() method.
I have these routes:
router.post('/totalbalance', (request, response) => {
const totalBalance = new TotalBalanceModelTemplate({
totalBalance:request.body.totalBalance,
});
totalBalance.save()
.then(data => {
response.json(data);
})
.catch(error => {
response.json(error);
});
});
router.get('/totalbalance', (request, response) => {
console.log("Response ", response);
});
This is axios request:
useEffect(() => {
console.log("Using get() method here");
axios.get('http://localhost:4000/app/totalbalance')
}, []);
However, it does not return anything (only 'Using get() method here' gets printed out to the console).
What am I missing here?
Thanks in advance!

How to await a build task in a VS Code extension?

let result = await vscode.commands.executeCommand('workbench.action.tasks.build');
resolves immediately.
How can I await a build task with VS Code API?
I figured it out! Tasks cannot be awaited from vscode.tasks.executeTask, but we can await vscode.tasks.onDidEndTask and check if ended task is our task.
async function executeBuildTask(task: vscode.Task) {
const execution = await vscode.tasks.executeTask(task);
return new Promise<void>(resolve => {
let disposable = vscode.tasks.onDidEndTask(e => {
if (e.execution.task.group === vscode.TaskGroup.Build) {
disposable.dispose();
resolve();
}
});
});
}
async function getBuildTasks() {
return new Promise<vscode.Task[]>(resolve => {
vscode.tasks.fetchTasks().then((tasks) => {
resolve(tasks.filter((task) => task.group === vscode.TaskGroup.Build));
});
});
}
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.commands.registerCommand('extension.helloWorld', async () => {
const buildTasks = await getBuildTasks();
await executeBuildTask(buildTasks[0]);
}));
}
Note that currently there is a bug #96643, which prevents us from doing a comparison of vscode.Task objects: if (e.execution.task === execution.task) { ... }
I think this depends on how the main command is executed in the extension.ts
Being new to JS/TS, I may be wrong here, but just trying to help:
make sure the vscode.command.registerCommand is not asyncronous, like below:
context.subscriptions.push(vscode.commands.registerCommand('extension.openSettings', () => {
return vscode.commands.executeCommand("workbench.action.openSettings", "settingsName");
}));
This would be compared to something async, like below:
context.subscriptions.push(vscode.commands.registerCommand('extension.removeHost', async (hostID) => {
const bigipHosts: Array<string> | undefined = vscode.workspace.getConfiguration().get('extension.hosts');
const newHosts = Hosts?.filter( item => item != hostID.label)
await vscode.workspace.getConfiguration().update('f5-fast.hosts', newBigipHosts, vscode.ConfigurationTarget.Global);
hostsTreeProvider.refresh();
}));

Mongoose not fetching data until I refresh the database connection

I am trying to re-fetch the data from MongoDB using mongoose whenever a user reloads the page. However, the old data stays there and the new data doesn't get fetched until I restart the server.
Here is the router:
router.post("/dashboard", (req, res) => {
const userId = req.body.userId;
User.findOne({ _id: userId }, (err, users) => {
if (err) {
console.log(err);
res.status(500).send();
} else {
router.get("/dashboard", (req, res, next) => {
const leagues = [users.leagues.premium, users.leagues.free];
if (err) return next(err);
res.status(200).send(leagues);
});
}
});
});
And here is the Actions (Redux):
export const fetchLeagues = userId => dispatch => {
axios.post("/api/leagues/dashboard", userId).then(
setTimeout(function() {
axios.get("/api/leagues/dashboard").then(leagues => {
dispatch({
type: GET_LEAGUES,
payload: leagues
});
});
}, 50)
);
};
The data must be fetched from a specific user, so that's why I am posting the user Id, then getting the data back. Not sure if this is the best way of doing this.
Just to clarify, I am using the MERN stack with redux and axios to execute this. I tried to use this: MongoDB does not refresh data automatically?, but I still can't get this thing to refresh/re-fetch the data when the router is called again. Thanks.
Doing a POST request then a GET request seems unnecessary here as you can just return the data in a single request.
The reason why the data is being persisted is because when you declare the router.get('/dashboard') route you are permanently hardcoding that route to have the values from the first request.
It's probably best to use a GET request, as that is what you are trying to do.
e.g.
router.get("/dashboard/:userId", (req, res) => {
const userId = req.params.userId;
User.findOne({ _id: userId }, (err, users) => {
if (err) {
console.log(err);
res.status(500).send();
} else {
const leagues = [users.leagues.premium, users.leagues.free];
if (err) return next(err);
res.status(200).send(leagues);
}
});
});
// Where userId is now a string
export const fetchLeagues = userId => dispatch => {
axios.get(`/api/leagues/dashboard/${userId}`).then(leagues => {
dispatch({
type: GET_LEAGUES,
payload: leagues
});
});
};