0

I am trying to assign Manager role to multiple members in one call. They're comma separated in the json. It sets for the first user in the comma separated values but it doesn't do for 2nd user. I am not sure where am I going wrong with this. I'm using Google Groups API. Any help would be appreciated as I'm new to using this and callback functions. Below is my JSON:

{
  "groupName":"TestGoogle5"
  "managerToBeAdded":"test1,test2",
  "memberSourceId":"g:gsa",
  "groupType":"group"
}

My typescript code:

searchGroup(groupName: string): GaxiosPromise<admin_directory_v1.Schema$Groups> {
       console.log("In search group")
        return this.googleService.groups.list({
            domain: this.googleDomain,
            query: `name=${groupName}`
        })
    }
addManagerToGroup(groupName: string, userId: string, retries: number = this.defaultRetries, delay: number = this.defaultDelay): Promise<any> {

        if (userId == "") {
            let msg = "Invalid userId"
            console.log(msg)
            return Promise.resolve(msg)
        }
        
        let userIdArray : Array <string> = []
        userIdArray= userId.indexOf(",") > -1 ? userId.split(",") : userId.split(" ");
        for (let entry of userIdArray) {
            return this.searchGroup(groupName).then((result) => {
                const groups = result.data.groups ?? []
                if (groups.length == 1) {
                    console.log("In If")
                    console.log(entry)
                    const groupKey = groups[0].id ?? ""
                    return this.googleService.members.insert({
                        groupKey,
                        requestBody: {
                            email: `${entry}@gmail.com`,
                            role: 'MANAGER',
                            delivery_settings: 'NONE',
                        }

                    }).catch(async (error: GaxiosError) => {
                        // membership already set, skipping message
                        if (error.message == "Member already exists.") {
                            let msg = `${entry} already exists as member of ${groupName}`
                            return Promise.resolve(msg)
                        }

                        
                        return Promise.reject(error)
                    })
                } else if (groups.length == 0) {
                    return Promise.reject("[UNRESOLVABLE_GROUP_EXCEPTION]: Could not find group with name " + groupName)
                } else if (groups.length >= 2) {
                    return Promise.reject("[MULTIPLE_GROUP_EXCEPTION]: Found multiple groups with name " + groupName + " !")
                }
            })
        }
        return Promise.resolve("Manager privilege set")
    }

Code that calls addManager

const _handlePrivilegeAdd = (gafeService: GAFEService, shortGroupName: string, userId: string, domain: string): Promise<any> => {
    return gafeService.addManagerToGroup(shortGroupName, userId)
        .catch((error: any) => {
            if (error.toString().includes("[UNRESOLVABLE_GROUP_EXCEPTION]")) {
                console.log("attempting to create group:\t" + shortGroupName)
                return gafeService
                    .createGroup(shortGroupName, _shortGroupNameToEmail(shortGroupName, domain), shortGroupName)
                    .then((groupAddResult: any) => {
                        //sleep for 5 seconds to let the group create propogate in google
                        return _later(5000)

                    })
                    .then(() => {
                        return gafeService.addManagerToGroup(shortGroupName, userId).then((results: any) => {
                            if (results == undefined) {
                                console.log("Not sure what causes this. Will fail the message.")
                                return Promise.reject("undefined")
                            }
                        })
                    })


            }
        })
        .then((results: any) => {
            if (results == undefined) {
                console.log("Not sure what causes this. Will fail the message.")
                return Promise.reject("undefined")
            }
            console.log(results)
            const resultMessage = `Successfully set ${userId} as a manager to ${shortGroupName} in GAFE.`
            console.log(resultMessage)
            return resultMessage
        })
}
  • I'm thinking the code is only executing the first iteration of your `for` loop because of the `return` keyword in this line `return this.searchGroup(groupName).then((result) => {`. Can you check if that's the case, by removing this keyword?: `this.searchGroup(groupName).then((result) => {`. – Iamblichus Nov 16 '20 at 09:46
  • Thanks you responding @Iamblichus, I did try that but then I think it calls the searchGroup which has a return and that directly steps to the next iteration instead of running the rest of the lines in for the loop. Callbacks are complicated lol – Ninjacompiler Nov 16 '20 at 12:54
  • I don't think the `return` in `searchGroup` should cause the iteration to be skipped. What makes you think that's the case? Also, could you provide the code related to `addManagerToGroup` being called? – Iamblichus Nov 16 '20 at 14:52
  • While testing, I had added console logs just to check the flow of the code and I see it jumps to the next iteration after hitting searchGroup when I removed the return from the part you suggested. I have added the part that calls the addManager method – Ninjacompiler Nov 16 '20 at 16:17
  • That's not what I'm experiencing. I wrote a code as similar to yours as possible, and if I remove the `return` keyword I mentioned before, I can add many members to the group at once, it doesn't skip the iterations. Can you please double-check this? – Iamblichus Nov 17 '20 at 12:02
  • I think I was able to make it work but I had a quick question, it sometimes adds members quickly and sometimes takes time. Is there a delay that should be added in the loop to let it wait before making another call to add manager? – Ninjacompiler Nov 18 '20 at 12:54
  • I cannot reproduce the behaviour you are mentioning, but in any case I'd suggest you to post another question for this. About `I think I was able to make it work`, can you explain what changes you did to make it work? I assume it was not removing the `return` keyword I suggested? – Iamblichus Nov 18 '20 at 13:22

0 Answers0