diff options
Diffstat (limited to 'lib/awprint/index.js')
| -rw-r--r-- | lib/awprint/index.js | 91 |
1 files changed, 91 insertions, 0 deletions
diff --git a/lib/awprint/index.js b/lib/awprint/index.js new file mode 100644 index 0000000..dec43fd --- /dev/null +++ b/lib/awprint/index.js @@ -0,0 +1,91 @@ +var bodyParser = require('body-parser') +var mongoose = require('mongoose') +var path = require('path') +mongoose.Promise = require('bluebird') +var socketIO = require('socket.io') + +function AWPrint (options) { + if (!(this instanceof AWPrint)) + return new AWPrint(options) + + options = options || {} + if (!options.express) + throw new Error('Express not provided to AWPrint'); + if (!options.config) + throw new Error('Configuration not provided to AWPrint'); + + var express = options.express + var router = express.Router() + var config = options.config + var io; + + var db, Print + + db = mongoose.connect(config.mongodbUrl) + mongoose.connection.on('error', (err) => { console.error("failed to start mongo!", err) }) + + var printSchema = new db.Schema({ + url: { + type: mongoose.Schema.Types.String, + required: true, + }, + printed: { + type: mongoose.Schema.Types.Boolean, + }, + date: { + type: mongoose.Schema.Types.Date, + }, + }) + var Print = db.model('Print', printSchema) + + router.use('/public/', express.static(path.join(__dirname, './public'))) + + router.get('/', function (req, res) { + res.sendFile(path.join(__dirname, 'public/index.html')) + }) + + router.get('/index', function (req, res) { + Print.find({}).sort('-date').limit(40).exec(function(err, docs) { + res.json(docs) + }) + }) + + router.post('/add', bodyParser.json({}), function (req, res) { + var data = { + url: req.body.url, + printed: false, + date: Date.now() + } + res.sendStatus(200) + new Print(data).save().then( (job) => { + io && io.emit('job', job) + }).catch( (err) => { + // idk + }) + }) + + router.post('/print', bodyParser.json({}), function (req, res) { + res.sendStatus(200) + Print.update({ _id: req.body._id }, { printed: true, }).then( (req) => { + // send a websocket message? + }).catch( (err) => { + // idk + }) + }) + + this._router = router + + // defer until the app is mounted + setImmediate(function(){ + io = socketIO(options.app._server) + io.on('connection', function(socket){ + // ... + }) + }) +} + +AWPrint.prototype.middleware = function () { + return this._router +} + +module.exports = AWPrint |
