From df1519a1810866f12e0b259c4e44b30a201780aa Mon Sep 17 00:00:00 2001 From: hydrabolt Date: Sun, 23 Aug 2015 19:55:54 +0100 Subject: [PATCH] added server caching --- src/server.js | 100 ++++++++++++++++++++++++++++++++------------------ 1 file changed, 65 insertions(+), 35 deletions(-) diff --git a/src/server.js b/src/server.js index a64a7114d..63cdf2ae9 100644 --- a/src/server.js +++ b/src/server.js @@ -1,39 +1,69 @@ -var User = require( "./user.js" ).User; -var List = require( "./list.js" ).List; -exports.Server = function( data ) { - this.region = data.region; - this.ownerID = data.owner_id; - this.name = data.name; - this.id = data.id; - this.members = new Map(); - this.channels = new Map(); - this.icon = data.icon; - this.afkTimeout = data.afk_timeout; - this.afkChannelId = data.afk_channel_id; +class Server { + constructor(data, client) { + this.client = client; + this.region = data.region; + this.ownerID = data.owner_id; + this.name = data.name; + this.id = data.id; + this.members = new Set(); + this.channels = new Set(); + this.icon = data.icon; + this.afkTimeout = data.afk_timeout; + this.afkChannelId = data.afk_channel_id; - for ( var x in members ) { - var member = members[ x ].user; - this.members.add( new User( member ) ); + for (var member of data.members) { + + // first we cache the user in our Discord Client, + // then we add it to our list. This way when we + // get a user from this server's member list, + // it will be identical (unless an async change occurred) + // to the client's cache. + this.members.add(client.addUser(member)); + + } + + for (var channel of data.channels) { + this.channels.add(client.addChannel(channel)); + } + } + + get iconURL() { + if (!this.icon) + return null; + return `https://discordapp.com/api/guilds/${this.id}/icons/${this.icon}.jpg`; + } + + get afkChannel() { + if (!this.afkChannelId) + return false; + + return this.getChannel("id", this.afkChannelId); + } + + get defaultChannel() { + return this.getChannel("name", "general"); + } + + // get/set + getChannel(key, value) { + for (var channel of this.channels) { + if (channel[key] === value) { + return channel; + } + } + + return null; + } + + getMember(key, value){ + for (var member of this.members) { + if (member[key] === value) { + return member; + } + } + + return null; } } -exports.Server.prototype.getIconURL = function(){ - if(!this.icon) - return false; - return "https://discordapp.com/api/guilds/"+this.id+"/icons/"+this.icon+".jpg"; -} - -exports.Server.prototype.getAFKChannel = function(){ - - if(!this.afkChannelId) - return false; - - return this.channels.filter("id", this.afkChannelId, true); - -} - -exports.Server.prototype.getDefaultChannel = function() { - - return this.channels.filter( "name", "general", true ); - -} +module.exports = Server; \ No newline at end of file