... this.me Docs modules/relationships.js

Source

modules/relationships.js

/**
 * @module Relationships
 * @description Methods to manage relationships for the `Me` class, with enforced relationship types and validation.
 */

// Define the allowed relationship types
const RELATIONSHIP_TYPES = [
  "friend", // Close personal connection
  "colleague", // Professional connection
  "family", // Familial connection
  "follower", // One-way follower (social media-like)
  "blocked", // Blocked user
  "group" // A group of related users
];

/**
 * Add a relationship to the `me` instance.
 * Enforces relationship types and allows additional metadata for extensibility.
 *
 * @function
 * @param {Array} relationships - The relationships array to update.
 * @param {Object} relationship - The relationship to add.
 * @param {string} relationship.type - The type of relationship (e.g., "friend", "colleague").
 * @param {string} relationship.username - The username of the related entity.
 * @param {Object} [relationship.meta] - Additional metadata for the relationship (optional).
 * @throws {Error} If the relationship type or username is invalid.
 * 
 * @example
 * // Adding a friend
 * addRelationship(relationships, { type: "friend", username: "alice" });
 * 
 * // Adding a group with metadata
 * addRelationship(relationships, { 
 *   type: "group", 
 *   username: "FamilyGroup", 
 *   meta: { members: ["alice", "bob"] } 
 * });
 */
export function addRelationship(relationships, { type, username, meta }) {
  if (!RELATIONSHIP_TYPES.includes(type)) {
    throw new Error(
      `Invalid relationship type: "${type}". Allowed types are: ${RELATIONSHIP_TYPES.join(", ")}`
    );
  }

  if (!username || typeof username !== "string") {
    throw new Error("Invalid or missing username for the relationship.");
  }

  // Push the validated relationship into the array
  relationships.push({ type, username, meta: meta || {} });
}

/**
 * Retrieve all relationships for the `me` instance, optionally filtered by type.
 *
 * @function
 * @param {Array} relationships - The relationships array to retrieve from.
 * @param {string} [type] - The type of relationship to filter by (e.g., "friend", "family").
 * @returns {Array} The filtered or full relationships array.
 * 
 * @example
 * // Get all relationships
 * getRelationships(relationships);
 * 
 * // Get only friends
 * getRelationships(relationships, "friend");
 */
export function getRelationships(relationships, type = null) {
  if (type) {
    return relationships.filter((rel) => rel.type === type);
  }
  return relationships;
}

By neurons.me