Skip to content

Commit

Permalink
perf(models: serverconfig): only save server config into cache for se…
Browse files Browse the repository at this point in the history
…rvers where messages are being

Now, it will first retrieve from cache, then from db, and ultimatelly create a new entry and add it
to the DB
  • Loading branch information
dsevillamartin committed May 21, 2018
1 parent ff03906 commit 7ca752d
Show file tree
Hide file tree
Showing 9 changed files with 53 additions and 52 deletions.
4 changes: 2 additions & 2 deletions lib/Discord/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,8 @@ class Client extends DiscordClient {
*/
async execute(msg) {
if (msg.author.equals(this.user) || msg.author.bot) return;
const serverConf = msg.guild && msg.guild.available ? ServerConfig.get(msg.guild.id) || await ServerConfig.add(msg.guild) : null;
const prefix = serverConf ? serverConf.prefix : Math.random();
const serverConf = msg.guild && msg.guild.available ? await ServerConfig.forServer(msg.guild) : null;
const prefix = serverConf ? serverConf.prefix : this.prefix;
if (msg.channel.type !== 'dm' && !msg.content.startsWith(this.user.toString()) && !msg.content.startsWith(prefix) && !msg.content.startsWith(this.prefix)) return false;

const content = (msg.content.startsWith(prefix) && msg.content.replace(prefix, '')) || (msg.content.startsWith(this.user.toString()) && msg.content.replace(`${this.user.toString()} `, '')) || (msg.content.startsWith(this.prefix) && msg.content.replace(this.prefix, '')) || msg.content;
Expand Down
8 changes: 4 additions & 4 deletions lib/Discord/Commands/GitlabInit.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class GitlabInitCommand extends Command {
if (exists) return this.commandError(msg, `Repository \`${repository.repo}\` is already initialized in this channel`);
return ChannelConfig.addRepoToChannel(channelid, repoFullName)
.then(() => {
let embed = this._successMessage(repository.repo);
let embed = this._successMessage(repository.repo, conf.embed);
return workingMsg.edit({ embed });
});
}
Expand All @@ -63,7 +63,7 @@ class GitlabInitCommand extends Command {
if (exists) return this.commandError(msg, `Repository \`${repository.repo}\` is already initialized in this channel`);
return ChannelConfig.addRepoToChannel(channelid, repoFullName)
.then(() => {
let embed = this._successMessage(repository.repo);
let embed = this._successMessage(repository.repo, conf.embed);
return workingMsg.edit({ embed });
});
}).catch(err => {
Expand All @@ -72,7 +72,7 @@ class GitlabInitCommand extends Command {
return this.commandError(msg, `Unable to initialize! The repository \`${repository.repo}\` could not be found!\nIf it's private, please add \`private\` after the command as a separate argument`);
});
}
_successMessage(repo) {
_successMessage(repo, hasEmbed) {
return {
color: 0x84F139,
footer: {
Expand All @@ -81,7 +81,7 @@ class GitlabInitCommand extends Command {
title: `\`${repo}\`: Successfully initialized repository events`,
description: [
'The repository must a webhook pointing to <https://www.yappybots.tk/gitlab>',
'To use embeds to have a nicer GitLab log, say `GL! conf set embed true` in this channel to enable embeds for the current channel.',
!hasEmbed && 'To use embeds to have a nicer GitLab log, say `GL! conf set embed true` in this channel to enable embeds for the current channel.',
].join('\n'),
};
}
Expand Down
2 changes: 1 addition & 1 deletion lib/Discord/Commands/GitlabInitOrg.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class GitlabInitOrgCommand extends Command {
let conf;

return Gitlab.getGroupProjects(orgName).then(async data => {
conf = ChannelConfig.get(channelid) || await ChannelConfig.add(msg.channel);
conf = await ChannelConfig.get(channelid);
const repos = data.body.filter(e => !conf.repos.includes(e.path_with_namespace.toLowerCase())).map(e => e.path_with_namespace);

return Promise.all(repos.map(repo => ChannelConfig.addRepoToChannel(channelid, repo))).then(() => repos);
Expand Down
2 changes: 1 addition & 1 deletion lib/Discord/Module.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class Module {
* @return {Promise<Message>}
*/
moduleError(msg, str) {
return msg.channel.sendMessage(`❌ ${str}`);
return msg.channel.send(`❌ ${str}`);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/Discord/Modules/CasualHelp.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ class CasualHelpModule extends Module {
domain: this.textToEmbed('Yappy Bots domain has expired', [
'Our domain https://www.yappybots.tk expired recently, and we did not get a notice.',
'The new domain is https://www.yappybots.tk, which will hopefully be temporary until we are able to get our old one back.',
'We apologize for the inconvinience.'
])
'We apologize for the inconvinience.',
]),
};
}

Expand Down
2 changes: 1 addition & 1 deletion lib/Discord/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ bot.on('ready', () => {
ServerConfig.init(bot);
});
bot.on('disconnect', (e) => {
Log.warn(`Bot | Disconnected (${e.code}).`)
Log.warn(`Bot | Disconnected (${e.code}).`);
logger.log('Disconnected', e.code, 'ORANGE');
});
bot.on('error', (e) => {
Expand Down
2 changes: 1 addition & 1 deletion lib/Gitlab/Events/wiki_page-create.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class WikiPageCreate extends EventResponse {
const page = data.object_attributes;
return [
`📰 **${actor}** created wiki page **${page.title}**`,
(page.content ? ` ${page.content.slice(0, 100).replace(/\n/g, ' ')}\n` : '') + `<${page.url}>`,
(page.content ? ` ${page.content.slice(0, 100).replace(/\n/g, ' ')}\n` : '') + `<${page.url}>`, // eslint-disable-line prefer-template
].join('\n');
}
}
Expand Down
6 changes: 4 additions & 2 deletions lib/Models/ChannelConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class ChannelConfigItem {
}
}

this.repos = this.repos || [];
this.repos = [...this.repos];
}
/**
* Set a specific config property to a value for this config item
Expand Down Expand Up @@ -153,7 +153,9 @@ class ChannelConfig {
if (!channel.name || !channel.guild.name || !channel.id) {
Log.warning('ChannelConf | Some info for channel not found', channel);
logger.log('Error when adding channel config to database', util.inspect(channel, { depth: 2 }), 'YELLOW');
} else this.add(channel).catch(e => bot.emit('error', e));
} else {
this.add(channel).catch(e => bot.emit('error', e));
}
});
}
}
Expand Down
75 changes: 37 additions & 38 deletions lib/Models/ServerConfig.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const mongoose = require('mongoose');
const Collection = require('discord.js').Collection;
const Schema = mongoose.Schema;
const ChannelConfig = require('./ChannelConfig');

Expand All @@ -24,8 +23,8 @@ const serverConfig = mongoose.model('ServerConfig', serverConfigSchema);
class ServerConfigItem {
constructor(client, config) {
/**
* The bot client
* @type Client
* The config manager
* @type ServerConfig
* @private
*/
this._client = client;
Expand All @@ -35,6 +34,7 @@ class ServerConfigItem {
}
}
}

/**
* Set a specific config property to a value for this config item
* @param {String} prop Property to modify
Expand All @@ -45,6 +45,7 @@ class ServerConfigItem {
set(prop, value) {
return this._client.set(this.guildID, prop, value);
}

/**
* Delete guild config
* @see ServerConfig#delete
Expand All @@ -62,11 +63,10 @@ class ServerConfig {
constructor() {
/**
* All the config
* @type {Collection}
* @type {WeakMap}
* @private
*/
this._data = new Collection();
this.setup();
this._data = new Map();
this.validKeys = [
'prefix',
];
Expand All @@ -78,37 +78,12 @@ class ServerConfig {
*/
this.loaded = false;
}
/**
* Get config from database and add to this._data
*/
setup() {
serverConfig.find({}).then(configs => {
this.loaded = true;
configs.forEach(row => {
if (!row.guildID) return;
this._data.set(row.guildID, new ServerConfigItem(this, row._doc));
});
});
}

/**
* Initialize configuration and Discord bot events
* @param {external:Client} bot Client instance
*/
init(bot) {
if (!this.loaded) {
setTimeout(() => this.init(bot), 5000);
return;
}

for (const g of bot.guilds) {
const guild = g[1];
if (!guild || !guild.available) continue;
if (!this.has(guild.id)) {
Log.info(`ServerConf | Adding "${guild.name}"`);
this.add(guild).catch(e => bot.emit('error', e));
}
}

if (!this.setupEvents) {
this.setupEvents = true;

Expand Down Expand Up @@ -139,13 +114,36 @@ class ServerConfig {
return serverConfig.findOneAndRemove({
guildID,
}).then(() => {
let oldData = this._data;
let newData = oldData.filter(e => e.guildID !== guildID);
this._data = newData;
return Promise.resolve(this);
this._data.delete(guildID);

return this;
});
}

/**
* Get server config for server, retreive from DB if not cached, create if non-existent
* @param {Server} server discord server object
* @return {ServerConfigItem}
*/
async forServer(server) {
return this._data.get(server.id) || this.addToCache(await serverConfig.findOne({ guildID: server.id }) || await this.add(server));
}

/**
* Add config item to cache
* @param {Mixed} item item to add to cache
* @return {ServerConfigItem}
*/
addToCache(item) {
if (item._doc) item = item._doc;
if (!(item instanceof ServerConfigItem)) item = new ServerConfigItem(this, item);
if (this._data.has(item.guildID)) return item;

this._data.set(item.guildID, item);

return item;
}

/**
* Add channel to config
* @param {Guild} guild Guild to add config of
Expand All @@ -159,9 +157,10 @@ class ServerConfig {
guildName: guild.name,
prefix: `GL! `,
};

return serverConfig.create(conf).then(() => {
this._data.set(conf.guildID, new ServerConfigItem(this, conf));
return Promise.resolve(this);
return this;
});
}

Expand All @@ -175,7 +174,7 @@ class ServerConfig {
set(guildID, prop, value) {
return new Promise((resolve, reject) => {
if (guildID.id) guildID = guildID.id;
let oldConfig = this._data.find('guildID', guildID);
let oldConfig = this._data.get(guildID);
let newConfig = oldConfig;
newConfig[prop] = value;
serverConfig.findOneAndUpdate({
Expand Down

0 comments on commit 7ca752d

Please sign in to comment.