diff --git a/ccm-core-apiclient/src/main/typescript/clients/groups-api.ts b/ccm-core-apiclient/src/main/typescript/clients/groups-api.ts new file mode 100644 index 000000000..3c9bbd403 --- /dev/null +++ b/ccm-core-apiclient/src/main/typescript/clients/groups-api.ts @@ -0,0 +1,81 @@ +import { + ApiResponse, + LibreCcmApiClient, + ListView, +} from "@libreccm/ccm-apiclient-commons"; + +import { Group, buildGroupFromRecord } from "../entities/group"; + +import * as Constants from "../constants"; +import { buildPartyRoleMembershipFromRecord } from "../entities/party"; +import { buildRoleFromRecord } from "../entities/role"; + +/** + * Client for managaging users, groups and roles using the RESTful API of + * LibreCCM. + */ +export class GroupsApiClient { + #apiClient: LibreCcmApiClient; + + readonly #GROUPS_API_PREFIX = `${Constants.ADMIN_API_PREFIX}/groups`; + + constructor(apiClient: LibreCcmApiClient) { + this.#apiClient = apiClient; + } + + async getGroups(limit: number, offset: number): Promise> { + try { + const response: ApiResponse = await this.#apiClient.get( + `${this.#GROUPS_API_PREFIX}`, + { + limit: limit.toString(), + offset: offset.toString(), + } + ); + if (response.ok) { + const result: Record< + string, + unknown + > = (await response.json()) as Record; + const list: Record[] = result.list as Record< + string, + unknown + >[]; + const groups: Group[] = list.map((record) => + buildGroupFromRecord(record) + ); + + return { + list: groups, + count: result.count as number, + limit: result.limit as number, + offset: result.offset as number, + }; + } else { + throw `Failed to get groups: + ${response.status} ${response.statusText}`; + } + } catch (err) { + throw `Failed to get groups: ${err}`; + } + } + + async getGroup(groupIdentifier: string): Promise { + try { + const response: ApiResponse = await this.#apiClient.get( + `${this.#GROUPS_API_PREFIX}/${groupIdentifier}` + ); + + if (response.ok) { + return buildGroupFromRecord( + (await response.json()) as Record + ); + } else { + throw `Failed to get group ${groupIdentifier}: + ${response.status} ${response.statusText}`; + } + } catch (err) { + throw `Failed to get group ${groupIdentifier}: ${err}`; + } + } +}