BVB Source Codes

mongo-express Show router.js Source code

Return Download mongo-express: download router.js Source code - Download mongo-express Source code - Type:.js
  1. 'use strict';
  2.  
  3. const _ = require('lodash');
  4. const basicAuth = require('basic-auth-connect');
  5. const bodyParser = require('body-parser');
  6. const cookieParser = require('cookie-parser');
  7. const db = require('./db');
  8. const errorHandler = require('errorhandler');
  9. const express = require('express');
  10. const favicon = require('serve-favicon');
  11. const logger = require('morgan');
  12. const methodOverride = require('method-override');
  13. const mongodb = require('mongodb');
  14. const routes = require('./routes');
  15. const session = require('express-session');
  16. const utils = require('./utils');
  17.  
  18. const router = function (config) {
  19.   // appRouter configuration
  20.   const appRouter = express.Router();
  21.   const mongo = db(config);
  22.  
  23.   if (config.useBasicAuth) {
  24.     appRouter.use(basicAuth(config.basicAuth.username, config.basicAuth.password));
  25.   }
  26.  
  27.   appRouter.use(favicon(__dirname + '/../public/images/favicon.ico'));
  28.  
  29.   appRouter.use(logger('dev', config.options.logger));
  30.  
  31.   appRouter.use('/public', express.static(__dirname + '/../build/'));
  32.  
  33.   // Set request size limit
  34.   appRouter.use(bodyParser.urlencoded({
  35.     extended: true,
  36.     limit: config.site.requestSizeLimit,
  37.   }));
  38.  
  39.   appRouter.use(cookieParser(config.site.cookieSecret));
  40.  
  41.   appRouter.use(session({
  42.     key: config.site.cookieKeyName,
  43.     resave: true,
  44.     saveUninitialized: true,
  45.     secret: config.site.sessionSecret,
  46.   }));
  47.  
  48.   appRouter.use(methodOverride(function (req) {
  49.     if (req.body && typeof req.body === 'object' && '_method' in req.body) {
  50.       // look in urlencoded POST bodies and delete it
  51.       const method = req.body._method;
  52.       delete req.body._method;
  53.       return method;
  54.     }
  55.   }));
  56.  
  57.   if (process.env.NODE_ENV === 'development') {
  58.     appRouter.use(errorHandler());
  59.   }
  60.  
  61.   const addTrailingSlash = function (s) {
  62.     return s + (s[s.length - 1] === '/' ? '' : '/');
  63.   };
  64.   const buildBaseHref = function (originalUrl, reqUrl) {
  65.     if (reqUrl === '/') {
  66.       return addTrailingSlash(originalUrl);
  67.     }
  68.     const idx = originalUrl.lastIndexOf(reqUrl);
  69.     const rootPath = originalUrl.substring(0, idx);
  70.     return addTrailingSlash(rootPath);
  71.   };
  72.  
  73.   // View helper, sets local variables used in templates
  74.   appRouter.all('*', function (req, res, next) {
  75.     res.locals.baseHref       = buildBaseHref(req.originalUrl, req.url);
  76.     res.locals.databases      = mongo.databases;
  77.     res.locals.collections    = mongo.collections;
  78.     res.locals.gridFSBuckets  = utils.colsToGrid(mongo.collections);
  79.  
  80.     // Flash messages
  81.     if (req.session.success) {
  82.       res.locals.messageSuccess = req.session.success;
  83.       delete req.session.success;
  84.     }
  85.  
  86.     if (req.session.error) {
  87.       res.locals.messageError = req.session.error;
  88.       delete req.session.error;
  89.     }
  90.  
  91.     if (config.mongodb.admin !== true) return next();
  92.  
  93.     mongo.updateDatabases(mongo.adminDb, function (databases) {
  94.       mongo.databases = databases;
  95.       res.locals.databases = mongo.databases;
  96.       return next();
  97.     });
  98.   });
  99.  
  100.   // route param pre-conditions
  101.   appRouter.param('database', function (req, res, next, id) {
  102.     //Make sure database exists
  103.     if (!_.includes(mongo.databases, id)) {
  104.       req.session.error = 'Database not found!';
  105.       return res.redirect(res.locals.baseHref);
  106.     }
  107.  
  108.     req.dbName = id;
  109.     res.locals.dbName = id;
  110.  
  111.     if (mongo.connections[id] !== undefined) {
  112.       req.db = mongo.connections[id];
  113.     } else {
  114.       mongo.connections[id] = mongo.mainConn.db(id);
  115.       req.db = mongo.connections[id];
  116.     }
  117.  
  118.     next();
  119.   });
  120.  
  121.   // :collection param MUST be preceded by a :database param
  122.   appRouter.param('collection', function (req, res, next, id) {
  123.     //Make sure collection exists
  124.  
  125.     if (!_.includes(mongo.collections[req.dbName], id)) {
  126.       req.session.error = 'Collection not found!';
  127.       return res.redirect(res.locals.baseHref + 'db/' + req.dbName);
  128.     }
  129.  
  130.     req.collectionName = id;
  131.     res.locals.collectionName = id;
  132.     res.locals.collections = mongo.collections[req.dbName];
  133.     res.locals.gridFSBuckets = utils.colsToGrid(mongo.collections[req.dbName]);
  134.  
  135.     mongo.connections[req.dbName].collection(id, function (err, coll) {
  136.       if (err || coll === null) {
  137.         req.session.error = 'Collection not found!';
  138.         return res.redirect(res.locals.baseHref + 'db/' + req.dbName);
  139.       }
  140.  
  141.       req.collection = coll;
  142.  
  143.       next();
  144.     });
  145.   });
  146.  
  147.   // :document param MUST be preceded by a :collection param
  148.   appRouter.param('document', function (req, res, next, id) {
  149.     if (id === 'undefined' || id === undefined) {
  150.       req.session.error = 'Document lacks an _id!';
  151.       return res.redirect(res.locals.baseHref + 'db/' + req.dbName + '/' + req.collectionName);
  152.     }
  153.  
  154.     id = JSON.parse(decodeURIComponent(id));
  155.     let obj_id;
  156.  
  157.     // Attempt to create ObjectID from passed 'id'
  158.     try {
  159.       obj_id = new mongodb.ObjectID.createFromHexString(id);
  160.     } catch (err) {
  161.       // Silence the error
  162.     }
  163.  
  164.     // If an ObjectID was correctly created from passed id param, try getting the ObjID first else falling back to try getting the string id
  165.     // If not valid ObjectID created, try getting string id
  166.  
  167.     if (obj_id) {
  168.       // passed id has successfully been turned into a valid ObjectID
  169.       req.collection.findOne({ _id: obj_id }, function (err, doc) {
  170.         if (err) {
  171.           req.session.error = 'Error: ' + err;
  172.           return res.redirect(res.locals.baseHref + 'db/' + req.dbName + '/' + req.collectionName);
  173.         }
  174.  
  175.         if (doc === null) {
  176.           // No document found with obj_id, try again with straight id
  177.           req.collection.findOne({ _id: id }, function (err, doc) {
  178.             if (err) {
  179.               req.session.error = 'Error: ' + err;
  180.               return res.redirect(res.locals.baseHref + 'db/' + req.dbName + '/' + req.collectionName);
  181.             }
  182.  
  183.             if (doc === null) {
  184.               req.session.error = 'Document not found!';
  185.               return res.redirect(res.locals.baseHref + 'db/' + req.dbName + '/' + req.collectionName);
  186.             }
  187.  
  188.             // Document found - send it back
  189.             req.document = doc;
  190.             res.locals.document = doc;
  191.  
  192.             next();
  193.           });
  194.         } else {
  195.           // Document found - send it back
  196.           req.document = doc;
  197.           res.locals.document = doc;
  198.  
  199.           next();
  200.         }
  201.  
  202.       });
  203.     } else {
  204.       // Passed id was NOT a valid ObjectID
  205.       req.collection.findOne({ _id: id }, function (err, doc) {
  206.         if (err) {
  207.           req.session.error = 'Error: ' + err;
  208.           return res.redirect(res.locals.baseHref + 'db/' + req.dbName + '/' + req.collectionName);
  209.         }
  210.  
  211.         if (doc === null) {
  212.           req.session.error = 'Document not found!';
  213.           return res.redirect(res.locals.baseHref + 'db/' + req.dbName + '/' + req.collectionName);
  214.         }
  215.  
  216.         req.document = doc;
  217.         res.locals.document = doc;
  218.  
  219.         next();
  220.       });
  221.     }
  222.   });
  223.  
  224.   // get individual property - for async loading of big documents
  225.   // (db)/(collection)/(document)/(prop)
  226.   appRouter.param('prop', function (req, res, next, prop) {
  227.     req.prop = req.document[prop];
  228.     next();
  229.   });
  230.  
  231.   // GridFS (db)/gridFS/(bucket)
  232.   appRouter.param('bucket', function (req, res, next, id) {
  233.  
  234.     req.bucketName = id;
  235.     res.locals.bucketName = id;
  236.  
  237.     mongo.connections[req.dbName].collection(id + '.files', function (err, filesConn) {
  238.       if (err || filesConn === null) {
  239.         req.session.error = id + '.files collection not found! Err:' + err;
  240.         return res.redirect(res.locals.baseHref + 'db/' + req.dbName);
  241.       }
  242.  
  243.       req.filesConn = filesConn;
  244.  
  245.       filesConn.find({}).toArray(function (err, files) {
  246.         if (err || files === null) {
  247.           req.session.error = id + '.files collection not found! Error:' + err;
  248.           return res.redirect(res.locals.baseHref + 'db/' + req.dbName);
  249.         }
  250.  
  251.         req.files = files;
  252.  
  253.         next();
  254.       });
  255.     });
  256.   });
  257.  
  258.   // GridFS files
  259.   appRouter.param('file', function (req, res, next, id) {
  260.     req.fileID = JSON.parse(decodeURIComponent(id));
  261.     next();
  262.   });
  263.  
  264.   // mongodb mongoMiddleware
  265.   const mongoMiddleware = function (req, res, next) {
  266.     req.mainConn = mongo.mainConn;
  267.     req.adminDb = mongo.adminDb;
  268.     req.databases = mongo.databases; //List of database names
  269.     req.collections = mongo.collections; //List of collection names in all databases
  270.     req.gridFSBuckets = utils.colsToGrid(mongo.collections);
  271.  
  272.     //Allow page handlers to request an update for collection list
  273.     req.updateCollections = mongo.updateCollections;
  274.  
  275.     next();
  276.   };
  277.  
  278.   // routes
  279.   const configuredRoutes = routes(config);
  280.  
  281.   appRouter.get('/', mongoMiddleware, configuredRoutes.index);
  282.   appRouter.post('/', mongoMiddleware, configuredRoutes.addDatabase);
  283.   appRouter.delete('/:database', mongoMiddleware, configuredRoutes.deleteDatabase);
  284.   appRouter.get('/db/:database', mongoMiddleware, configuredRoutes.viewDatabase);
  285.  
  286.   appRouter.post('/checkValid', mongoMiddleware, configuredRoutes.checkValid);
  287.  
  288.   // Collection level routes
  289.   appRouter.get('/db/:database/compact/:collection', mongoMiddleware, configuredRoutes.compactCollection);
  290.   appRouter.get('/db/:database/expArr/:collection', mongoMiddleware, configuredRoutes.exportColArray);
  291.   appRouter.get('/db/:database/expCsv/:collection', mongoMiddleware, configuredRoutes.exportCsv);
  292.   appRouter.get('/db/:database/reIndex/:collection', mongoMiddleware, configuredRoutes.reIndex);
  293.   appRouter.get('/db/:database/export/:collection', mongoMiddleware, configuredRoutes.exportCollection);
  294.   appRouter.get('/db/:database/dropIndex/:collection', mongoMiddleware, configuredRoutes.dropIndex);
  295.   appRouter.get('/db/:database/updateCollections', mongoMiddleware, configuredRoutes.updateCollections);
  296.  
  297.   // GridFS
  298.   appRouter.post('/db/:database/gridFS', mongoMiddleware, configuredRoutes.addBucket);
  299.   appRouter.delete('/db/:database/gridFS/:bucket', mongoMiddleware, configuredRoutes.deleteBucket);
  300.  
  301.   appRouter.get('/db/:database/gridFS/:bucket', mongoMiddleware, configuredRoutes.viewBucket);
  302.   appRouter.post('/db/:database/gridFS/:bucket', mongoMiddleware, configuredRoutes.addFile);
  303.   appRouter.get('/db/:database/gridFS/:bucket/:file', mongoMiddleware, configuredRoutes.getFile);
  304.   appRouter.delete('/db/:database/gridFS/:bucket/:file', mongoMiddleware, configuredRoutes.deleteFile);
  305.  
  306.   appRouter.get('/db/:database/:collection', mongoMiddleware, configuredRoutes.viewCollection);
  307.   appRouter.put('/db/:database/:collection', mongoMiddleware, configuredRoutes.renameCollection);
  308.   appRouter.delete('/db/:database/:collection', mongoMiddleware, configuredRoutes.deleteCollection);
  309.   appRouter.post('/db/:database', mongoMiddleware, configuredRoutes.addCollection);
  310.  
  311.   // Document routes
  312.   appRouter.post('/db/:database/:collection', mongoMiddleware, configuredRoutes.addDocument);
  313.   appRouter.get('/db/:database/:collection/:document', mongoMiddleware, configuredRoutes.viewDocument);
  314.   appRouter.put('/db/:database/:collection/:document', mongoMiddleware, configuredRoutes.updateDocument);
  315.   appRouter.delete('/db/:database/:collection/:document', mongoMiddleware, configuredRoutes.deleteDocument);
  316.  
  317.   // Property routes
  318.   appRouter.get('/db/:database/:collection/:document/:prop', mongoMiddleware, configuredRoutes.getProperty);
  319.  
  320.   return appRouter;
  321. };
  322.  
  323. module.exports = router;
  324.  
downloadrouter.js Source code - Download mongo-express Source code
Related Source Codes/Software:
XCL-Charts - Android charting libraries (XCL-Charts is a free c... 2017-05-17
scrollMonitor - A simple and fast API to monitor elements as you s... 2017-05-16
XCDYouTubeKit - YouTube video player for iOS, tvOS and macOS 2017-05-16
rails-erd - Generate Entity-Relationship Diagrams for Rails ap... 2017-05-16
np - A better `npm publish` 2017-05-16
kaminari - A Scope & Engine based, clean, powerful, custo... 2017-06-04
python-fire - Python Fire is a library for automatically generat... 2017-06-04
Dapper - Dapper - a simple object mapper for .Net 2017-06-05
pkg - Package your Node.js project into an executable ... 2017-06-05
packer - Packer is a tool for creating identical machine im... 2017-06-05
CRYENGINE - CRYENGINE is a powerful real-time game development... 2017-06-11
postal - 2017-06-11
reactide - Reactide is the first dedicated IDE for React web ... 2017-06-11
rkt - rkt is a pod-native container engine for Linux. It... 2017-06-11
uWebSockets - Tiny WebSockets https://for... 2017-06-11
realworld - TodoMVC for the RealWorld - Exemplary fullstack Me... 2017-06-11
goreplay - GoReplay is an open-source tool for capturing and ... 2017-06-10
pyenv - Simple Python version management 2017-06-10
redux-saga - An alternative side effect model for Redux apps ... 2017-06-10
angular-starter - 2017-06-10

 Back to top