Give and receive constructive feedback from your fellow campers on Algorithm Challenge solutions, Frontend and Backend projects
// service
export const getUserByUsername = username => new Promise(async function(resolve, reject) {
const userData = await dbgetUserByUsername(username);
const user = userModelFactory(userData);
if(validateUser(user)) {
resolve(user);
} else {
reject();
}
});
//model
export const dbgetUserByUsername = username => getdb().collection('users').find({ username }).toArray((err, result) => (err || result));
//route
router.get('/user/:username', handleasyncreq(req => getUserByUsername(req.params.username)
.then(result => ({ body: result }))
.catch(result => ({ body: result, status: 400 }))
));
//handleasyncreq code
export function handleasyncreq(f) {
async function asynchandler(req, res) {
const { status = 200, headers = {}, body = {} } = await f(req);
res.status(status).set(headers).json(body);
}
return asynchandler;
}
@abeledovictor I personally feel like the code you posted it too complex for its own good. Your mixing async/await
with normal promises, your own async handler function, and new Promise
, even tho you have async/await
code.
For such a simple case, you should be fine with just the route, service and maybe the model. I also don't believe in using .then
and .catch
if your using async/await
. It's more important to stay consistent than to do "one-liners" for the same of one-liners.
Great code is dirt easy to read and understand. Don't be clever/shorter just for the sake of it.
without getting to verbose (I'm to lazy to write out all your code hehe)
I would have this:
// route
router.get('/user/:username', (req, res) => {
try {
const {username} = req.params;
const user = await getUserByUsername(username);
res.send({status: 200, body: user});
} catch (err) {
res.send({body: err, status: 400});
}
});
// getUserByUsername service
// NOTE: if your using async await, you automatically return promises from this function
export const getUserByUsername =(username) => {
const user = userModelFactory(dbGetUserByUsername(username)); // this function is the same
if (validateUser(user) {
return user;
}
throw Error();
}
The dbGetUserByUsername
function is the same
new Promise
code. I feel like using them saves you a few lines, but were like 1 or 2 lines here or there haha
await
next to the dbGetUserByUsername
call aswell hehe