50
loading...
This website collects cookies to deliver better user experience
async function plantTreesForTeamCarbon() {
try {
const users = db.query(`
SELECT * FROM users
WHERE team = 'carbon';
`;)
for(user of users) {
if (user.tokens >= 3) {
const res = await fetch('https://planttreesinmynameyoufilthyanimal.com', {
method: 'post',
body: JSON.stringify({
username: user.username,
numberOfTrees: Math.floor(user.tokens / 3),
}),
headers: {
'Content-Type': 'application/json',
'Authorization': process.env.API_KEY,
},
});
db.query(`
UPDATE users
SET
tokens = ${user.tokens % 3},
trees_planted = ${user.trees_planted + (Math.floor(user.tokens / 3))}
WHERE user_id = ${user.user_id};
`;);
}
}
} catch (err) {
console.error(err);
}
}
async function plantTreesForTeam(team) {
const users = await getUsersFromTeam(team);
for (user of users) {
const { treesToPlant, remainingTokens } = calculateNumberOfTrees(
user.tokens
);
if (!treesToPlant) continue;
const plantTrees = await plantTreesForUser(user.user_id, treesToPlant);
await Promise.all([
db.updateUserTokens(user.user_id, user.tokens),
db.updateUserTrees(user.user_id, remainingTokens),
]);
}
}
getUsersFromTeam()
function, for example, they can click through to view it, but the important part is they don't have to in order to understand what it does. It's very clear just from the name and context what it does, and that's the point! So from the top down, we can see how each line / function has a single purpose and doesn't care about anything outside of it:plantTreesForTeam()
plants trees for a team.getUsersFromTeam()
gets users from a team.calculateNumberOfTrees()
calculates the number of trees to plant based on token quantity.if (!treesToPlant) continue;
breaks the loop if there are no trees to plant.plantTreesForUser()
plants trees for a single user.Promise.all()
that updates our database asynchronously, but inside that, db.updateUserTokens()
updates a user's token count, and db.updateUserTrees()
updates a user's planted tree count.[err, success]
array to make error handling even simpler, but I'll save that design pattern for another post.