mirror of
https://github.com/discordjs/discord.js.git
synced 2026-03-13 01:53:30 +01:00
Add toJSON methods (#1859)
* tojson things * fix client * ignore private properties * remove extra property descriptors * handle primitive flattening * remove unused import * add toJSON to collections * reduce stateful props * state * allow custom prop names when flattening * fix client * fix build * fix flatten docs * remove guild.available, cleanup permissions, remove arbitrary id reduction * fix util import * add valueOf as needed, update member props * fix incorrect merge * update permissionoverwrites and permissions remove serialization of permissions in PermissionOverwrites#toJSON. change Permissions#toJSON to serialize permissions, by default excluding admin checks. * change Permissions#toJSON to return the primitive * Permissions#toJSON explicitly return bitfield
This commit is contained in:
@@ -12,6 +12,41 @@ class Util {
|
||||
throw new Error(`The ${this.constructor.name} class may not be instantiated.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flatten an object. Any properties that are collections will get converted to an array of keys.
|
||||
* @param {Object} obj The object to flatten.
|
||||
* @param {...Object<string, boolean|string>} [props] Specific properties to include/exclude.
|
||||
* @returns {Object}
|
||||
*/
|
||||
static flatten(obj, ...props) {
|
||||
const isObject = d => typeof d === 'object' && d !== null;
|
||||
if (!isObject(obj)) return obj;
|
||||
|
||||
props = Object.assign(...Object.keys(obj).filter(k => !k.startsWith('_')).map(k => ({ [k]: true })), ...props);
|
||||
|
||||
const out = {};
|
||||
|
||||
for (let [prop, newProp] of Object.entries(props)) {
|
||||
if (!newProp) continue;
|
||||
newProp = newProp === true ? prop : newProp;
|
||||
|
||||
const element = obj[prop];
|
||||
const elemIsObj = isObject(element);
|
||||
const valueOf = elemIsObj && typeof element.valueOf === 'function' ? element.valueOf() : null;
|
||||
|
||||
// If it's a collection, make the array of keys
|
||||
if (element instanceof require('./Collection')) out[newProp] = Array.from(element.keys());
|
||||
// If it's an array, flatten each element
|
||||
else if (Array.isArray(element)) out[newProp] = element.map(e => Util.flatten(e));
|
||||
// If it's an object with a primitive `valueOf`, use that value
|
||||
else if (valueOf && !isObject(valueOf)) out[newProp] = valueOf;
|
||||
// If it's a primitive
|
||||
else if (!elemIsObj) out[newProp] = element;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a string into multiple chunks at a designated character that do not exceed a specific length.
|
||||
* @param {string} text Content to split
|
||||
|
||||
Reference in New Issue
Block a user