Skip to content

Instantly share code, notes, and snippets.

@trevorstarick
Created December 11, 2014 06:59
Show Gist options
  • Save trevorstarick/e115e8f604b315f7d3a0 to your computer and use it in GitHub Desktop.
Save trevorstarick/e115e8f604b315f7d3a0 to your computer and use it in GitHub Desktop.
Basic Example
/*jslint node: true */
'use strict';
var mongoose = require('mongoose');
mongoose.set('debug', true);
var u = 'mongodb://xxxx:xxxxxxxxx@xxx.xxxxx.xxxxx';
var db = mongoose.createConnection(u);
var collection = db.model('test', new mongoose.Schema({}), 'test');
api.index = function(req, res) {
res.status(200)send('Ok');
};
api.getItem = function(req, res) {
var id = req.query.id;
collection.find({
_id: id
})
.lean()
.exec(function(err, docs) {
if (err) throw err;
res.json(docs);
})
};
module.exports = api
/*jslint node: true */
'use strict';
var http = require('http');
var https = require('https');
var bodyParser = require('body-parser');
var express = require('express');
var logger = require('morgan');
var api = require('./routes.js');
// JSONP output hack
express.response.jsonp = function(obj) {
// settings
var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
var callback = this.req.query[app.get('jsonp callback name')];
this.set('Content-Type', 'application/json');
if (Array.isArray(callback)) {
callback = callback[0];
}
// jsonp
if (callback && 'string' === typeof callback) {
this.set('Content-Type', 'text/javascript');
var cb = callback.replace(/[^\[\]\w$.]/g, '');
body = cb + '(' + body + ');';
}
return this.send(body);
};
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.set('jsonp callback name', 'callback');
app.set('json replacer', " ");
// Set CORS
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
// Routing
app.get('/', api.index);
app.get('/get', api.itemAvailability);
// Server prefs
var options = {
cert: fs.readFileSyn('./keys/xxxx.crt'), // S
key: fs.readFileSync('./keys/xxxx.key'), // S
ca: fs.readFileSync('./keys/bundle.crt') // L
};
var devmode = process.argv[2] === 'DEV' ? true : false;
if (devmode) {
http.createServer(app).listen(3000);
} else {
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment