This repository has been archived on 2024-09-23. You can view files and clone it, but cannot push or open issues or pull requests.
rocketchat-scim/rc-sdk/RcSdk.ts
2022-02-15 13:38:33 +01:00

96 lines
2.8 KiB
TypeScript

import {
IHttp,
IHttpRequest,
IHttpResponse,
IRead,
} from "@rocket.chat/apps-engine/definition/accessors";
import { EmptyResponseError } from "../errors/EmptyResponseError";
import { JsonParseError } from "../errors/JsonParseError";
import { RcSdkTeam } from "./RcSdkTeam";
import { RcSdkUser } from "./RcSdkUser";
export class RcSdk {
public user: RcSdkUser;
public team: RcSdkTeam;
private readonly baseUrl = "http://localhost:3000/api/v1";
private readonly http: IHttp;
private readonly read: IRead;
constructor(http: IHttp, read: IRead) {
this.http = http;
this.read = read;
this.user = new RcSdkUser(this);
this.team = new RcSdkTeam(this);
}
public async get(url: string, content?: any): Promise<IHttpResponse> {
return this.http.get(
this.buildUrl(url),
await this.buildOptions(content),
);
}
public async post(url: string, content?: any): Promise<IHttpResponse> {
return this.http.post(
this.buildUrl(url),
await this.buildOptions(content),
);
}
public async put(url: string, content?: any): Promise<IHttpResponse> {
return this.http.put(
this.buildUrl(url),
await this.buildOptions(content),
);
}
public async del(url: string, content?: any): Promise<IHttpResponse> {
return this.http.del(
this.buildUrl(url),
await this.buildOptions(content),
);
}
public async patch(url: string, content?: any): Promise<IHttpResponse> {
return this.http.patch(
this.buildUrl(url),
await this.buildOptions(content),
);
}
public parseResponse(response: IHttpResponse): any {
if (!response.content) {
throw new EmptyResponseError();
}
let content: any;
try {
content = JSON.parse(response.content);
} catch (e) {
throw new JsonParseError();
}
return content;
}
private buildUrl(url: string): string {
return `${this.baseUrl}/${url}`;
}
private async buildOptions(content?: any): Promise<IHttpRequest> {
const options: IHttpRequest = {
headers: {
"X-User-Id": await this.read
.getEnvironmentReader()
.getSettings()
.getValueById("rc-user-id"),
"X-Auth-Token": await this.read
.getEnvironmentReader()
.getSettings()
.getValueById("rc-token"),
"Content-Type": "application/json",
},
};
if (content !== undefined) {
options.content = JSON.stringify(content);
}
return options;
}
}