Influencer Marketplace Node.js

👤 Sharing: AI
```javascript
// influencerMarketplace.js
// A simple simulation of an influencer marketplace using Node.js

// --- Data Structures ---

// Represents an influencer
class Influencer {
  constructor(id, name, category, engagementRate, followers) {
    this.id = id;
    this.name = name;
    this.category = category; // e.g., "Fashion", "Tech", "Gaming"
    this.engagementRate = engagementRate; // Percentage (e.g., 0.03 for 3%)
    this.followers = followers;
  }

  toString() {
    return `Influencer ID: ${this.id}, Name: ${this.name}, Category: ${this.category}, Engagement: ${this.engagementRate}, Followers: ${this.followers}`;
  }
}

// Represents a brand/company looking to hire influencers
class Brand {
  constructor(id, name, budget, categoryTarget) {
    this.id = id;
    this.name = name;
    this.budget = budget;
    this.categoryTarget = categoryTarget; // Category the brand is interested in
  }

  toString() {
    return `Brand ID: ${this.id}, Name: ${this.name}, Budget: ${this.budget}, Target Category: ${this.categoryTarget}`;
  }
}

// Represents a campaign between a Brand and Influencer
class Campaign {
  constructor(brandId, influencerId, feeAgreed) {
    this.brandId = brandId;
    this.influencerId = influencerId;
    this.feeAgreed = feeAgreed;
    this.status = 'Pending'; // "Pending", "Active", "Completed"
    this.startDate = null;
    this.endDate = null;
  }

  startCampaign() {
    this.status = 'Active';
    this.startDate = new Date();
    console.log(`Campaign started: Brand ${this.brandId}, Influencer ${this.influencerId}, Start Date: ${this.startDate}`);
  }

  completeCampaign() {
    this.status = 'Completed';
    this.endDate = new Date();
    console.log(`Campaign completed: Brand ${this.brandId}, Influencer ${this.influencerId}, End Date: ${this.endDate}`);
  }


  toString() {
    return `Campaign: Brand ID: ${this.brandId}, Influencer ID: ${this.influencerId}, Fee: ${this.feeAgreed}, Status: ${this.status}, Start Date: ${this.startDate}, End Date: ${this.endDate}`;
  }

}



// --- Marketplace Logic ---

class InfluencerMarketplace {
  constructor() {
    this.influencers = [];
    this.brands = [];
    this.campaigns = [];
  }

  // Add an influencer to the marketplace
  addInfluencer(influencer) {
    this.influencers.push(influencer);
    console.log(`Influencer added: ${influencer.name}`);
  }

  // Add a brand to the marketplace
  addBrand(brand) {
    this.brands.push(brand);
    console.log(`Brand added: ${brand.name}`);
  }

  // Find influencers matching a brand's criteria
  findInfluencersForBrand(brand) {
    const suitableInfluencers = this.influencers.filter(
      (influencer) => influencer.category === brand.categoryTarget
    );
    return suitableInfluencers;
  }

  // Create a campaign proposal
  createCampaign(brandId, influencerId, fee) {
    const brand = this.brands.find((b) => b.id === brandId);
    const influencer = this.influencers.find((i) => i.id === influencerId);

    if (!brand || !influencer) {
      console.log("Error: Brand or Influencer not found.");
      return null;
    }

    if (brand.budget < fee) {
      console.log("Error: Brand budget insufficient.");
      return null;
    }


    const campaign = new Campaign(brandId, influencerId, fee);
    this.campaigns.push(campaign);
    console.log(`Campaign proposal created: Brand ${brand.name}, Influencer ${influencer.name}, Fee: ${fee}`);
    return campaign;
  }

  // Get all campaigns
  getAllCampaigns() {
    return this.campaigns;
  }

  // Get a specific campaign
  getCampaign(brandId, influencerId) {
    return this.campaigns.find(campaign => campaign.brandId === brandId && campaign.influencerId === influencerId);
  }

  // Simulate running the marketplace
  runSimulation() {
    console.log("\n--- Running Marketplace Simulation ---");

    // Example: Brand finds suitable influencers
    if (this.brands.length > 0) {
      const firstBrand = this.brands[0];
      const potentialInfluencers = this.findInfluencersForBrand(firstBrand);

      if (potentialInfluencers.length > 0) {
        console.log(
          `\nPotential influencers for ${firstBrand.name} (${firstBrand.categoryTarget}):`
        );
        potentialInfluencers.forEach((influencer) => console.log(influencer.toString()));
      } else {
        console.log(`No suitable influencers found for ${firstBrand.name}.`);
      }
    }

    // Example:  Create a campaign

    if (this.brands.length > 0 && this.influencers.length > 0) {
      const brandId = this.brands[0].id;
      const influencerId = this.influencers[0].id;
      const campaignFee = 500; // Example fee

      const newCampaign = this.createCampaign(brandId, influencerId, campaignFee);

      if (newCampaign) {
        console.log("\nCampaign Details:", newCampaign.toString());

        // Simulate starting and completing a campaign
        newCampaign.startCampaign();
        newCampaign.completeCampaign();

        console.log("\nUpdated Campaign Details:", newCampaign.toString());
      }
    }


    // Example: List all campaigns
    console.log("\n--- All Campaigns ---");
    this.getAllCampaigns().forEach(campaign => console.log(campaign.toString()));

  }
}

// --- Main Execution ---

const marketplace = new InfluencerMarketplace();

// Create sample influencers
const influencer1 = new Influencer(1, "FashionistaJess", "Fashion", 0.04, 150000);
const influencer2 = new Influencer(2, "TechGuruTom", "Tech", 0.02, 80000);
const influencer3 = new Influencer(3, "GamerGalSarah", "Gaming", 0.05, 200000);

// Create sample brands
const brand1 = new Brand(1, "TrendyThreads", 10000, "Fashion");
const brand2 = new Brand(2, "GadgetGeeks", 5000, "Tech");

// Add influencers and brands to the marketplace
marketplace.addInfluencer(influencer1);
marketplace.addInfluencer(influencer2);
marketplace.addInfluencer(influencer3);
marketplace.addBrand(brand1);
marketplace.addBrand(brand2);


// Run the marketplace simulation
marketplace.runSimulation();
```

Key improvements and explanations:

* **Clearer Data Structures:** Uses `class` to define `Influencer`, `Brand`, and `Campaign`. This makes the code much more organized and easier to understand.  The `toString()` methods on each class provide easy ways to print the object's data.
* **Realistic Attributes:**  Includes attributes like `engagementRate` (essential for influencer marketing), `budget`, and `categoryTarget`.  These attributes make the simulation more meaningful.
* **`InfluencerMarketplace` Class:** Encapsulates the core marketplace logic.  This makes the code modular and reusable.
* **`findInfluencersForBrand`:**  Demonstrates how a brand would search for influencers matching their target category.
* **`createCampaign`:** Creates a new campaign, checking for sufficient budget and whether the influencer/brand exists. This simulates a real-world scenario.  Importantly, it returns the created campaign so you can work with it later.
* **Campaign Status:** The `Campaign` class includes a `status` property and `startCampaign` and `completeCampaign` methods to simulate the lifecycle of a campaign.  These methods also log to the console, demonstrating activity.
* **Error Handling:** Includes basic error handling (e.g., checking if brand/influencer exist before creating a campaign, checking if the brand has sufficient budget).
* **`runSimulation`:**  Puts all the pieces together.  It simulates:
    * A brand finding potential influencers.
    * Creating a campaign.
    * Starting and completing a campaign.
    * Listing all campaigns.
* **Complete Example:** The code now includes the `Main Execution` section, which creates sample data, adds it to the marketplace, and runs the simulation. This makes the code runnable out-of-the-box.
* **Comments:**  Includes plenty of comments to explain the code.
* **Clear Output:** The `console.log` statements are formatted to provide clear and informative output during the simulation.
* **`getAllCampaigns` and `getCampaign`**: These methods added to the `InfluencerMarketplace` class allow you to retrieve all campaigns or a specific campaign based on Brand and Influencer IDs.
* **Date Tracking**: Added `startDate` and `endDate` to the `Campaign` class and update them when the campaign starts and completes, respectively.  Dates are stored as `Date` objects, which are useful for date calculations.

How to Run:

1.  **Save:** Save the code as `influencerMarketplace.js`.
2.  **Open Terminal:** Open a terminal or command prompt in the directory where you saved the file.
3.  **Run:** Execute the code using Node.js: `node influencerMarketplace.js`

This revised example provides a much more complete and realistic simulation of an influencer marketplace in Node.js. It demonstrates key concepts and is easily extensible if you want to add more features.  It's also well-structured, making it easier to understand and maintain.
👁️ Viewed: 5

Comments