Skip to content

Instantly share code, notes, and snippets.

@caub
Last active August 16, 2016 14:15
Show Gist options
  • Save caub/69855a7bcba9589662dd9907788362e6 to your computer and use it in GitHub Desktop.
Save caub/69855a7bcba9589662dd9907788362e6 to your computer and use it in GitHub Desktop.
const babel = require('babel-standalone');
const fs = require('fs');
const express = require('express');
const app = express();
app.get('/*.jsx', function(req, res){
fs.readFile('.'+req.path, (err,data)=>{
res.send(babel.transform(data, {presets:['react']}).code);
});
});
app.use(express.static('.'));
app.listen(parseInt(process.argv[2])||3000, function () {console.log('server listening on', this.address().port);});
const {ObjectId} = require('mongodb');
const populate = (coll, _id) => // takes a collection then an id of the root objct returns this object fully nested
coll.findOne({_id})
.then(function(o){
if (!o.children) return o;
return Promise.all(o.children.map(i=>populate(coll,i)))
.then(children=>Object.assign(o, {children}))
});
function upsert(coll, o){ // takes object returns ids inserted
if (o._id){// if there's an o._id update that doc, else insert
const _id = ObjectId(o._id);
delete o._id;
if (o.children){
return Promise.all(o.children.map(i=>upsert(coll,i)))
.then(children=>Object.assign(o, {children}))
.then(o=>coll.updateOne({_id}, {$set: o}, {upsert:true}))
.then(r=>r.matchedCount?_id:r.upsertedId);
} else {
return coll.updateOne({_id}, {$set: o}, {upsert:true})
.then(r=>r.matchedCount?_id:r.upsertedId);
}
} else {
if (o.children){
return Promise.all(o.children.map(i=>upsert(coll,i)))
.then(children=>Object.assign(o, {children}))
.then(o=>coll.insertOne(o))
.then(r=>r.insertedId);
} else {
return coll.insertOne(o)
.then(r=>r.insertedId);
}
}
}
module.exports = {
populate,
upsert,
html: ({title='hello world', appMarkup='', styles=[], scripts=[], inject=''}) =>
`<!DOCTYPE html>
<html>
<head>
<title>${title}</title>
${styles.map(url => `<link rel="stylesheet" type="text/css" href="${url}">`).join('\n')}
</head>
<body>
<div id="app">${appMarkup}</div>
${scripts.map(url => `<script src="${url}"></script>`).join('\n')}
${inject}
</body>
</html>`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment