session-open-group-server-l.../storage.js

84 lines
2.3 KiB
JavaScript
Raw Normal View History

const funcs = [];
funcs.push(require('./models/users.js'));
funcs.push(require('./models/challenges.js'));
funcs.push(require('./models/roles.js'));
funcs.push(require('./models/user_roles.js'));
funcs.push(require('./models/role_permissions.js'));
2019-11-08 04:41:18 +01:00
const Schema = require('caminte').Schema
const memoryUpdate = (model, filter, data, callback) => {
2019-11-08 04:41:18 +01:00
'use strict';
if ('function' === typeof filter) {
return filter(new Error('Get parametrs undefined'), null);
2019-11-08 04:41:18 +01:00
}
if ('function' === typeof data) {
return data(new Error('Set parametrs undefined'), null);
2019-11-08 04:41:18 +01:00
}
filter = filter.where ? filter.where : filter;
2019-11-12 02:51:49 +01:00
const mem = this;
2019-11-08 04:41:18 +01:00
// filter input to make sure it only contains valid fields
2019-11-12 02:51:49 +01:00
const cleanData = this.toDatabase(model, data);
2019-11-08 04:41:18 +01:00
if (data.id) {
// should find one and only one
this.exists(model, data.id, function (err, exists) {
if (exists) {
mem.save(model, Object.assign(exists, cleanData), callback);
2019-11-08 04:41:18 +01:00
} else {
callback(err, cleanData);
2019-11-08 04:41:18 +01:00
}
})
} else {
this.all(model, filter, function(err, nodes) {
2019-11-12 02:51:49 +01:00
if (!nodes.length) {
return callback(false, cleanData);
2019-11-08 04:41:18 +01:00
}
nodes.forEach(function(node) {
mem.cache[model][node.id] = Object.assign(node, cleanData);
});
2019-11-12 02:51:49 +01:00
callback(false, cleanData);
});
2019-11-08 04:41:18 +01:00
}
}
function start(config) {
// schema backend type
const schemaType = 'memory';
const options = {};
const schema = new Schema(schemaType, options);
2019-11-08 04:41:18 +01:00
if (schemaType === 'memory') {
schema.adapter.update = memoryUpdate;
2019-11-08 04:41:18 +01:00
}
if (schemaType==='mysql') {
//charset: "utf8_general_ci" / utf8mb4_general_ci
// run a query "set names utf8"
schema.client.changeUser({ charset: 'utf8mb4' }, function(err) {
if (err) console.error('Couldnt set UTF8mb4', err);
});
2019-11-08 04:41:18 +01:00
// to enable emojis we may need to run these
// alter table X MODIFY `Y` type CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
2019-11-08 04:41:18 +01:00
}
2019-11-12 02:51:49 +01:00
const modelOptions = {
2019-11-08 04:41:18 +01:00
schema: schema,
};
2019-11-08 04:41:18 +01:00
funcs.forEach((func) => {
func.start(modelOptions);
2019-11-08 04:41:18 +01:00
});
if (schemaType=='mysql' || schemaType=='sqlite3') {
//schema.automigrate(function() {});
2019-11-08 04:41:18 +01:00
// don't lose data
schema.autoupdate(function() {});
2019-11-08 04:41:18 +01:00
}
}
2019-11-12 02:51:49 +01:00
module.exports = {};
funcs.map(func => Object.assign(module.exports, func));
2019-11-08 04:41:18 +01:00
// override all those starts
module.exports.start = start;