From 0815d7fc7f8ab3edf6fb2969f5904b60686feb51 Mon Sep 17 00:00:00 2001 From: "supa-creation.com" Date: Sat, 4 Nov 2017 14:21:47 +0100 Subject: [PATCH] Add TTL index configuration --- lib/mongoCache.js | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/lib/mongoCache.js b/lib/mongoCache.js index 7156d72..dd5b1c2 100644 --- a/lib/mongoCache.js +++ b/lib/mongoCache.js @@ -4,11 +4,34 @@ var MongoClient = require('mongodb').MongoClient; var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/prerender'; +var mongoTtl = process.env.MONGODB_CACHE_TTL || null; var database; -MongoClient.connect(mongoUri, function(err, db) { +MongoClient.connect(mongoUri, function (err, db) { database = db; + + if (mongoTtl) { + database.collection('pages', function (err, collection) { + collection.indexes(function (err, indexes) { + var existTtlIndex = false; + + indexes.forEach(function (index) { + var isTtlIndex = JSON.stringify(index.key) == JSON.stringify({created: 1}); + if (isTtlIndex && index.expireAfterSeconds == mongoTtl) { + existTtlIndex = true; + } else if (isTtlIndex) { + collection.dropIndex(index.name); + } + }); + + if (!existTtlIndex) { + console.log('createIndex'); + collection.ensureIndex({"created": 1}, {expireAfterSeconds: mongoTtl}); + } + }); + }); + } }); var cache_manager = require('cache-manager');