First part of API client for managing groups

Former-commit-id: c9f879df94
restapi
Jens Pelzetter 2020-07-31 17:23:03 +02:00
parent 1c5961a75c
commit cb0d700a24
1 changed files with 81 additions and 0 deletions

View File

@ -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<ListView<Group>> {
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<string, unknown>;
const list: Record<string, unknown>[] = 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<Group> {
try {
const response: ApiResponse = await this.#apiClient.get(
`${this.#GROUPS_API_PREFIX}/${groupIdentifier}`
);
if (response.ok) {
return buildGroupFromRecord(
(await response.json()) as Record<string, unknown>
);
} else {
throw `Failed to get group ${groupIdentifier}:
${response.status} ${response.statusText}`;
}
} catch (err) {
throw `Failed to get group ${groupIdentifier}: ${err}`;
}
}
}