codecombat/server/commons/database.coffee

35 lines
1.3 KiB
CoffeeScript
Raw Normal View History

config = require '../../server_config'
winston = require 'winston'
mongoose = require 'mongoose'
Grid = require 'gridfs-stream'
mongooseCache = require 'mongoose-cache'
global.testing = testing = '--unittest' in process.argv
module.exports.connect = () ->
address = module.exports.generateMongoConnectionString()
winston.info "Connecting to Mongo with connection string #{address}"
mongoose.connect address
mongoose.connection.once 'open', -> Grid.gfs = Grid(mongoose.connection.db, mongoose.mongo)
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
mongooseCache.install(mongoose, {max: 200, maxAge: 1 * 60 * 1000, debug: false}, Aggregate)
module.exports.generateMongoConnectionString = ->
2014-05-05 20:33:47 -04:00
if not testing and config.mongo.mongoose_replica_string
address = config.mongo.mongoose_replica_string
else
dbName = config.mongo.db
dbName += '_unittest' if testing
2014-06-30 22:16:26 -04:00
address = config.mongo.host + ':' + config.mongo.port
if config.mongo.username and config.mongo.password
2014-06-30 22:16:26 -04:00
address = config.mongo.username + ':' + config.mongo.password + '@' + address
address = "mongodb://#{address}/#{dbName}"
2014-05-05 20:33:47 -04:00
return address