alphascript-server
Version:
CRUD operations for mongo and other functionalities to get started quickly in any CMS project
229 lines (190 loc) • 7.95 kB
JavaScript
var fs = require('fs');
var passport = require('passport');
var express = require('express');
function API() {
this.schemaOptions = function () {
return {
emitIndexErrors: true,
strict: false,
autoIndex: true,
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
},
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
};
};
this.mongoOptions = function () {
return {
poolSize: 5,
bufferCommands: false,
bufferMaxEntries: 0,
autoIndex: true,
keepAlive: 250,
autoReconnect: true,
reconnectTries: 30,
reconnectInterval: 500,
};
};
}
API.prototype.config = function (options) {
//setup options
options.mongoose = options.mongoose || require('mongoose');
this.options = options;
//setup database driver
var framework = require('./lib/util');
framework = mergeJSON(framework, require('./lib/log'), "util");
framework = mergeJSON(framework, require('./lib/auth'), "log");
framework = mergeJSON(framework, require('./lib/db')(), "auth");
for (var key in framework) {
if (typeof this[key] !== 'undefined') console.log("warning! " + key + " object overwritten");
this[key] = framework[key];
}
};
API.prototype.db = function (key, model) {
this.db[key] = model;
if (typeof model === 'function') console.log(key + ' (db models): function');
else logMap(key + ' (db models)', model);
};
API.prototype.init = function () {
//setup passport
passport.use(this.auth.method.strategy);
passport.serializeUser(this.auth.method.serializeUser);
passport.deserializeUser(this.auth.method.deserializeUser);
this.passport = passport;
this.common.init();
logMap('common (db models)', this.common);
//permission map
var apiPermissions = JSON.parse(fs.readFileSync(__dirname + '/lib/auth/permissions.json'));
var appPermissions = this.options.permissionsConfig ? JSON.parse(fs.readFileSync(this.options.permissionsConfig)) : null;
if (typeof this.permissionMap !== 'undefined') console.log("warning! permissionMap object overwritten");
this.permissionMap = mergeJSON(apiPermissions, appPermissions, "permissions");
//entity map
var entityDirs = [__dirname + '/lib/assets/entity'].concat(this.options.entityRoot);
this.entityMap = loadDirectories('entity', entityDirs);
logMap('entities', this.entityMap);
//task map
var taskDirs = [__dirname + '/lib/assets/task'].concat(this.options.taskRoot);
this.taskMap = loadDirectories('task', taskDirs);
logMap('tasks', this.taskMap);
this.task.load();
//graph map
var graphDirs = [__dirname + '/lib/assets/graph'].concat(this.options.graphRoot);
this.graphMap = loadDirectories('graph', graphDirs);
logMap('graphs', this.graphMap);
//list map
var listDirs = [__dirname + '/lib/assets/list'].concat(this.options.listRoot);
this.listMap = loadDirectories('list', listDirs);
logMap('lists', this.listMap);
//report map
var reportDirs = [__dirname + '/lib/assets/report'].concat(this.options.reportRoot);
this.reportMap = loadDirectories('report', reportDirs);
logMap('reports', this.reportMap);
//setup routings
var router = express.Router({
caseSensitive: true
});
router.get('/api/logo', function (req, res) {
res.sendFile(api.options.clientLogoPath);
});
//authentication & authorization
router.post('/api/session/login', this.auth.login);
router.get('/api/session/logout', this.auth.logout);
router.get('/api/session/currentuser', this.auth.user);
if (typeof this.entityMap.user.getOwners === 'function') {
router.get('/api/user/owners', this.entityMap.user.getOwners);
}
router.get('/api/role/permissions', this.auth.getPermissionMap);
router.post('/api/user/activate', this.auth.method.activateAccount);
router.post('/api/user/changepassword', this.auth.method.changePassword);
router.post('/api/user/resetpassword', this.auth.method.resetPassword);
//mongo driver dependent functionality
router.get('/api/document/download/:id', this.document.download);
router.post('/api/image/upload/:key', this.document.uploadImage);
router.get('/api/address/pt/:zipcode', this.address.get);
router.get('/api/task/types', this.task.getTypes);
router.get('/api/task/run/:id', this.task.run);
router.get('/api/task/toggle/:id', this.task.toggle);
router.get('/api/message/list/:db', this.message.get);
router.get('/api/activity/list/:db', this.activity.get);
router.get('/api/error/list/:db', this.error.get);
//todo remove mongo dependency
router.get('/api/report/metadata', this.metadata.getMetadata);
for (var listKey in this.listMap) {
router.get('/api/list/values/:db/' + listKey, this.list.getList(listKey));
}
router.get('/api/list/getall', this.list.getMetadata);
for (var reportKey in this.reportMap) {
router.get('/api/report/metadata/' + reportKey, this.report.getMetadata(reportKey));
router.get('/api/report/get/:namespace/:db/' + reportKey, this.report.getReport(reportKey));
}
//db driver independent functionality
router.get('/api/unit/measure/:type?', this.measure.getByType);
router.get('/api/unit/describe/:unit', this.measure.describeUnit);
router.get('/api/unit/convert/:unit', this.measure.convertPossibilities);
router.get('/api/unit/convert/:value/:from/:to', this.measure.convert);
router.post('/api/graph/auto/:namespace/:db/:collection/:driver?', this.graph.get);
for (var graphKey in this.graphMap) {
router.get('/api/graph/custom/:namespace/:db/' + graphKey + '/:driver?', this.graph.custom(graphKey));
}
for (var entityKey in this.entityMap) {
router.get('/api/' + entityKey + '/list/:db/:id?', this.entity.redirectToDriver(entityKey, "_list"));
router.post('/api/' + entityKey + '/add/:db/:id?', this.entity.redirectToDriver(entityKey, "edit"));
router.get('/api/' + entityKey + '/fetch/:db', this.entity.redirectToDriver(entityKey, "fetch"));
router.post('/api/' + entityKey + '/update/:db/:id', this.entity.redirectToDriver(entityKey, "update"));
router.get('/api/' + entityKey + '/remove/:db/:id', this.entity.redirectToDriver(entityKey, "remove"));
router.get('/api/' + entityKey + '/versions/:db/:id', this.entity.redirectToDriver(entityKey, "versions"));
router.get('/api/' + entityKey + '/pdf/:db/:id?', this.entity.redirectToDriver(entityKey, "pdf"));
router.get('/api/' + entityKey + '/xlsx/:db/:id?', this.entity.redirectToDriver(entityKey, "xlsx"));
}
this.router = router;
};
var api = module.exports = exports = new API;
function logMap(name, map) {
var keys = [];
for (var key in map) {
keys.push(key);
}
console.log(name + ': ' + keys.join());
}
function loadDirectories(key, paths) {
var result = {};
paths.forEach(function (path) {
//load entities on path
var items;
try {
items = fs.readdirSync(path);
} catch (err) {
return;
}
var regexp = /^[a-zA-Z0-9-]*$/;
(items || []).forEach(function (item) {
//svn for windows generates a /.svn folder
if (item.startsWith('.')) return;
if (!regexp.test(item)) return;
if (typeof result[item] !== 'undefined') console.log(item + ' entity overwritten');
result[item] = require(path + '/' + item + '/' + item + '.' + key + '.js');
});
});
return result;
}
function mergeJSON(base, object, context) {
if (!object) return base;
if (!context) context = "api";
for (var key in object) {
if (typeof base[key] === 'undefined') base[key] = {};
else console.log(key + ' overwritten @' + context);
for (var subKey in object[key]) {
if (typeof base[key][subKey] === 'undefined') base[key][subKey] = {};
else console.log(key + '/' + subKey + ' overwritten @' + context);
base[key][subKey] = object[key][subKey];
}
}
return base;
}
API.prototype.test = require('./lib/test/');