Teams: Bulk Assign Members (JavaScript)

View as Markdown

This script is designed to bulk assign existing members to a specific team, using the email address of each member as an identifier. It operates by reading a list of email addresses from a .member-emails file, finding each member’s ID through the Sigma API, then assigning each member to a designated team.

Each section of the script has inline comments provided.

Refer to the Sigma REST API Recipes QuickStart for step-by-step instructions.

Example script

JavaScript
1// This script bulk assigns existing members to a team, based on the members's email, which is matched from the "../.member-emails" file.
2// Load required modules and environment variables for script configuration.
3
4require('dotenv').config({ path: 'sigma-api-recipes/.env' });
5const getBearerToken = require('../get-access-token'); // Function to obtain an authentication token.
6const axios = require('axios'); // HTTP client for making requests to Sigma's API.
7const fs = require('fs'); // File system module to read the list of emails from a file.
8const path = require('path'); // Module for handling file paths.
9
10// Environment variables loaded from the .env file.
11const baseURL = process.env.baseURL; // Base URL for Sigma's API endpoints.
12const teamId = process.env.TEAMID; // Target team ID for assigning members.
13const emailListPath = path.join(__dirname, '..', '.member-emails'); // Path to the file containing member emails.
14
15// Function to find a member's ID by their email address.
16async function findMemberIdByEmail(email, token) {
17 const encodedEmail = encodeURIComponent(email); // Encode email to ensure it is URL-safe.
18 const requestUrl = `${baseURL}/members?search=${encodedEmail}`; // Construct the request URL.
19 console.log(`Searching for member by email with URL: ${requestUrl}`); // Log the request for debugging.
20 try {
21 const response = await axios.get(requestUrl, {
22 headers: { Authorization: `Bearer ${token}` }, // Include the bearer token for authentication.
23 });
24 // Return the first matching member ID if found.
25 return Array.isArray(response.data) && response.data.length > 0 ? response.data[0].memberId : null;
26 } catch (error) {
27 console.error(`Error searching for member by email (${email}):`, error);
28 return null; // Return null if an error occurs or no member is found.
29 }
30}
31
32// Function to add a member to a specified team by their member ID.
33async function addMemberToTeam(memberId, teamId, token) {
34 const requestUrl = `${baseURL}/teams/${teamId}/members`; // API endpoint for adding a member to a team.
35 const payload = { add: [memberId], remove: [] }; // Payload specifying the member to add (and none to remove).
36 const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }; // Request headers.
37
38 // Log the request details for debugging.
39 console.log(`Adding member to team with URL: ${requestUrl}`);
40 // console.log(`Headers:`, JSON.stringify(headers, null, 2));
41 console.log(`Payload:`, JSON.stringify(payload, null, 2));
42
43 try {
44 const response = await axios.patch(requestUrl, payload, { headers });
45 console.log(`Member ${memberId} added to team ${teamId}. Response:`, response.data);
46 } catch (error) {
47 console.error(`Error adding member ${memberId} to team ${teamId}:`, error.response ? error.response.data : error);
48 }
49}
50
51// Main function to process member emails and assign them to the specified team.
52async function processMembers(teamId, token) {
53 const emails = fs.readFileSync(emailListPath, 'utf-8').split(','); // Read and split the list of emails.
54 for (const email of emails) {
55 const memberId = await findMemberIdByEmail(email.trim(), token); // Get member ID by email.
56 if (memberId) {
57 await addMemberToTeam(memberId, teamId, token); // Add the member to the team.
58 } else {
59 console.log(`Member not found for email: ${email}`); // Log if no member ID is found for an email.
60 }
61 }
62}
63
64// Entry point of the script.
65async function main() {
66 const token = await getBearerToken(); // Fetch the bearer token.
67 if (!token) {
68 console.error('Failed to obtain bearer token.');
69 return;
70 }
71 await processMembers(teamId, token); // Process member assignments.
72}
73
74main().catch(console.error); // Execute the main function and catch any errors.

Endpoints used

  1. Get authentication token: getBearerToken function
  2. Find member by email: ${baseURL}/members?search=${encodedEmail}
  3. Add member to team: ${baseURL}/teams/${teamId}/members