2014-02-04 15:30:05 -05:00
|
|
|
config = require '../../server_config'
|
|
|
|
winston = require 'winston'
|
|
|
|
mongoose = require 'mongoose'
|
|
|
|
Grid = require 'gridfs-stream'
|
2015-02-26 20:20:27 -05:00
|
|
|
mongooseCache = require 'mongoose-cache'
|
2014-02-04 15:30:05 -05:00
|
|
|
|
|
|
|
module.exports.connect = () ->
|
2014-02-10 13:30:08 -05:00
|
|
|
address = module.exports.generateMongoConnectionString()
|
2014-02-10 16:18:39 -05:00
|
|
|
winston.info "Connecting to Mongo with connection string #{address}"
|
2014-02-10 13:30:08 -05:00
|
|
|
|
|
|
|
mongoose.connect address
|
2014-02-10 16:18:39 -05:00
|
|
|
mongoose.connection.once 'open', -> Grid.gfs = Grid(mongoose.connection.db, mongoose.mongo)
|
2014-02-10 13:30:08 -05:00
|
|
|
|
2015-02-26 21:32:59 -05:00
|
|
|
# Hack around Mongoose not exporting Aggregate so that we can patch its exec, too
|
|
|
|
# https://github.com/LearnBoost/mongoose/issues/1910
|
|
|
|
Level = require '../levels/Level'
|
|
|
|
Aggregate = Level.aggregate().constructor
|
2015-12-05 11:18:36 -05:00
|
|
|
maxAge = (Math.random() * 10 + 10) * 60 * 1000 # Randomize so that each server doesn't refresh cache from db at same times
|
|
|
|
mongooseCache.install(mongoose, {max: 1000, maxAge: maxAge, debug: false}, Aggregate)
|
2014-02-10 13:30:08 -05:00
|
|
|
|
|
|
|
module.exports.generateMongoConnectionString = ->
|
2015-12-09 17:27:10 -05:00
|
|
|
if not global.testing and config.tokyo
|
2015-03-19 14:18:38 -04:00
|
|
|
address = config.mongo.mongoose_tokyo_replica_string
|
2015-12-09 17:27:10 -05:00
|
|
|
else if not global.testing and config.saoPaulo
|
2015-09-02 12:33:48 -04:00
|
|
|
address = config.mongo.mongoose_saoPaulo_replica_string
|
2015-12-09 17:27:10 -05:00
|
|
|
else if not global.testing and config.mongo.mongoose_replica_string
|
2014-02-04 15:30:05 -05:00
|
|
|
address = config.mongo.mongoose_replica_string
|
|
|
|
else
|
|
|
|
dbName = config.mongo.db
|
2015-12-09 17:27:10 -05:00
|
|
|
dbName += '_unittest' if global.testing
|
2014-06-30 22:16:26 -04:00
|
|
|
address = config.mongo.host + ':' + config.mongo.port
|
2014-02-04 15:30:05 -05:00
|
|
|
if config.mongo.username and config.mongo.password
|
2014-06-30 22:16:26 -04:00
|
|
|
address = config.mongo.username + ':' + config.mongo.password + '@' + address
|
2014-02-04 15:30:05 -05:00
|
|
|
address = "mongodb://#{address}/#{dbName}"
|
2014-02-10 13:30:08 -05:00
|
|
|
|
2014-05-05 20:33:47 -04:00
|
|
|
return address
|