Skip to content

Instantly share code, notes, and snippets.

View thebopshoobop's full-sized avatar

Will Timpson thebopshoobop

View GitHub Profile
const display = (res, items) => {
let lines = [];
items.forEach(item => {
lines.push("<hr>");
lines.push([`${item.name}: $${item.price}`]);
});
lines = lines.join("<br>");
res.writeHead(200, { "Content-Type": "text/html" });
res.end(lines);
};
const opts = {
most: () => [{}, {}, { sort: { price: -1 } }],
least: (most) => [{ category: most.category }, {}, { sort: { price: 1 } }],
sum: (most, least) => {
return [
[
{
$match: {
category: most.category,
_id: { $nin: [most._id, least._id] }
app.get("/callback", (req, res) => {
const errCall = e => {
res.status(500).end(e.stack);
};
Product.findOne(...mostOpts(), (err, most) => {
if (err) return errCall(err);
Product.findOne(...leastOpts(most), (err, least) => {
if (err) return errCall(err);
Product.aggregate(...sumOpts(most, least), (err, sum) => {
if (err) return errCall(err);
Product.findOne(...mostOpts())
.then(most => {
Product.findOne(...leastOpts(most))
.then(least => { //... })
// ...
Product.findOne(...mostOpts())
.then(most => {
return Promise.all([ most, Product.findOne(...leastOpts(most)) ]);
})
.spread(most, least => { //... })
// ...
app.get("/promise", (req, res) => {
let most;
let least;
Product.findOne(...mostOpts())
.then(m => {
most = m;
return Product.findOne(...leastOpts(most));
})
.then(l => {
least = l;
app.get("/async", async (req, res) => {
try {
const most = await Product.findOne(...mostOpts());
const least = await Product.findOne(...leastOpts(most));
const sum = await Product.aggregate(...sumOpts(most, least));
display(res, [most, least, sum[0]]);
} catch (e) {
res.status(500).end(e.stack);
}
});
// non-sequential actions
const promises = [ Product.find(), Category.find() ]
// handling with plain promises
Promise.all(promises)
.spread((products, categories) => {
doLiterallyAnything(products, categories)
});
// handling with await
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const uniqueValidator = require("mongoose-unique-validator");
const bcrypt = require("bcrypt");
const UserSchema = new Schema({
username: { type: String, required: true, unique: true },
passwordHash: { type: String, required: true }
});
const passport = require("passport");
app.use(passport.initialize());
app.use(passport.session());