import { request , IRequestOptions , ArcGISRequestError } from "@esri/arcgis-rest-request" ; import { getPortalUrl } from "../util/get-portal-url" ; import { chunk } from "../util/array" ; export interface IAddGroupUsersOptions extends IRequestOptions { /**
     * Group ID
     */ id : string ; /**
     * An array of usernames to be added to the group as group members
     */ users ? : string [ ] ; /**
     * An array of usernames to be added to the group as group admins
     */ admins ? : string [ ] ; } export interface IAddGroupUsersResult { /**
     * An array of usernames that were not added
     */ notAdded ? : string [ ] ; /**
     * An array of request errors
     */ errors ? : ArcGISRequestError [ ] ; } param requestOptions returns export function addGroupUsers ( requestOptions ) { const id = requestOptions . id ; const url = `${ getPortalUrl ( requestOptions ) }/community/groups/${ id }/addUsers` ; const baseOptions = Object . assign ( { } , requestOptions , { admins : undefined , users : undefined } ) ; const batchRequestOptions = [ ... _prepareRequests ( "users" , requestOptions . users , baseOptions ) , ... _prepareRequests ( "admins" , requestOptions . admins , baseOptions ) ] ; const promises = batchRequestOptions . map ( options => _sendSafeRequest ( url , options ) ) ; return Promise . all ( promises ) . then ( _consolidateRequestResults ) ; } function _prepareRequests ( type , usernames , baseOptions ) { if ( ! usernames || usernames . length < 1 ) { return [ ] ; } const userChunks = chunk < string > ( usernames , 25 ) ; return userChunks . map ( users => _generateRequestOptions ( type , users , baseOptions ) ) ; } function _generateRequestOptions ( type , usernames , baseOptions ) { return Object . assign ( { } , baseOptions , { [ type ] : usernames , params : { ... baseOptions . params , [ type ] : usernames } } ) ; } function _sendSafeRequest ( url , requestOptions ) { return request ( url , requestOptions ) . catch ( error => { return { errors : [ error ] } ; } ) ; } function _consolidateRequestResults ( results ) { const notAdded = results . filter ( result => result . notAdded ) . reduce ( ( collection , result ) => collection . concat ( result . notAdded ) , [ ] ) ; const errors = results . filter ( result => result . errors ) . reduce ( ( collection , result ) => collection . concat ( result . errors ) , [ ] ) ; const consolidated = { notAdded } ; if ( errors . length > 0 ) { consolidated . errors = errors ; } return consolidated ; }