Managers_GuildManager.js

'user strict'
const Discord = require('discord.js')
const { Guild } = require('../Structures/Guild')
const { ErrorCodes } = require('../Errors/ErrorCodes')
const { BaseManager } = require('./BaseManager')
const { MissingValue, InvalidValue } = require('../Errors/LME')

/**
 * Manager for the guilds, is different from the Discord.js GuildManager.
 * @extends {BaseManager<Guild>}
 */
class GuildManager extends BaseManager {
  /**
   * @param {Discord.Client} client - The Discord Client.
   * @param {Guild[]} iterable - Array of guilds.
   */
  constructor (client, iterable) {
    super(client, Guild)

    if (!iterable) throw new MissingValue(ErrorCodes.MissingArgument, 'iterable')

    if (!Array.isArray(iterable)) throw new InvalidValue(ErrorCodes.InvalidValue, 'iterable', 'an array')

    for (const item of iterable) {
      this._add(item)
    }
  }

  /**
   * Add a new guild to the cache.
   * @param {Guild} guild - Guild to add.
   * @returns {Guild} - The added guild.
   * @private
   * @ignore
   */
  _add (guild) {
    if (!(guild instanceof Guild)) throw new InvalidValue(ErrorCodes.InvalidValue, 'guild', 'a Guild instance')

    const existing = this.cache.has(guild.guildId)
    if (existing) return existing

    this.cache.set(guild.guildId, guild)

    return guild
  }
}

module.exports = { GuildManager }