buddy

node MVC discord bot
Log | Files | Refs | README

UserManager.js (1950B)


      1 'use strict';
      2 
      3 const BaseManager = require('./BaseManager');
      4 const GuildMember = require('../structures/GuildMember');
      5 const Message = require('../structures/Message');
      6 const User = require('../structures/User');
      7 
      8 /**
      9  * Manages API methods for users and stores their cache.
     10  * @extends {BaseManager}
     11  */
     12 class UserManager extends BaseManager {
     13   constructor(client, iterable) {
     14     super(client, iterable, User);
     15   }
     16 
     17   /**
     18    * The cache of this manager
     19    * @type {Collection<Snowflake, User>}
     20    * @name UserManager#cache
     21    */
     22 
     23   /**
     24    * Data that resolves to give a User object. This can be:
     25    * * A User object
     26    * * A Snowflake
     27    * * A Message object (resolves to the message author)
     28    * * A GuildMember object
     29    * @typedef {User|Snowflake|Message|GuildMember} UserResolvable
     30    */
     31 
     32   /**
     33    * Resolves a UserResolvable to a User object.
     34    * @param {UserResolvable} user The UserResolvable to identify
     35    * @returns {?User}
     36    */
     37   resolve(user) {
     38     if (user instanceof GuildMember) return user.user;
     39     if (user instanceof Message) return user.author;
     40     return super.resolve(user);
     41   }
     42 
     43   /**
     44    * Resolves a UserResolvable to a user ID string.
     45    * @param {UserResolvable} user The UserResolvable to identify
     46    * @returns {?Snowflake}
     47    */
     48   resolveID(user) {
     49     if (user instanceof GuildMember) return user.user.id;
     50     if (user instanceof Message) return user.author.id;
     51     return super.resolveID(user);
     52   }
     53 
     54   /**
     55    * Obtains a user from Discord, or the user cache if it's already available.
     56    * @param {Snowflake} id ID of the user
     57    * @param {boolean} [cache=true] Whether to cache the new user object if it isn't already
     58    * @returns {Promise<User>}
     59    */
     60   async fetch(id, cache = true) {
     61     const existing = this.cache.get(id);
     62     if (existing && !existing.partial) return existing;
     63     const data = await this.client.api.users(id).get();
     64     return this.add(data, cache);
     65   }
     66 }
     67 
     68 module.exports = UserManager;