Files
SCM-Manager/scm-ui-components/packages/ui-components/src/apiclient.js

91 lines
2.3 KiB
JavaScript
Raw Normal View History

// @flow
import {contextPath} from "./urls";
2018-12-07 14:26:06 +01:00
export const NOT_FOUND_ERROR = new Error("not found");
export const UNAUTHORIZED_ERROR = new Error("unauthorized");
export const CONFLICT_ERROR = new Error("conflict");
const fetchOptions: RequestOptions = {
credentials: "same-origin",
headers: {
2018-07-10 15:18:37 +02:00
Cache: "no-cache"
}
};
function handleStatusCode(response: Response) {
if (!response.ok) {
2018-11-15 08:40:13 +01:00
switch (response.status) {
case 401:
throw UNAUTHORIZED_ERROR;
2018-11-15 08:40:13 +01:00
case 404:
throw NOT_FOUND_ERROR;
2018-12-07 14:26:06 +01:00
case 409:
throw CONFLICT_ERROR;
2018-11-15 08:40:13 +01:00
default:
throw new Error("server returned status code " + response.status);
}
2018-11-15 08:40:13 +01:00
}
return response;
}
export function createUrl(url: string) {
if (url.includes("://")) {
return url;
}
let urlWithStartingSlash = url;
2018-07-11 22:01:36 +02:00
if (url.indexOf("/") !== 0) {
urlWithStartingSlash = "/" + urlWithStartingSlash;
2018-07-11 22:01:36 +02:00
}
2018-10-01 17:22:03 +02:00
return `${contextPath}/api/v2${urlWithStartingSlash}`;
}
class ApiClient {
get(url: string): Promise<Response> {
return fetch(createUrl(url), fetchOptions).then(handleStatusCode);
}
post(url: string, payload: any, contentType: string = "application/json") {
return this.httpRequestWithJSONBody("POST", url, contentType, payload);
}
put(url: string, payload: any, contentType: string = "application/json") {
return this.httpRequestWithJSONBody("PUT", url, contentType, payload);
2018-07-11 17:02:38 +02:00
}
2018-10-25 13:45:52 +02:00
head(url: string) {
let options: RequestOptions = {
method: "HEAD"
};
options = Object.assign(options, fetchOptions);
return fetch(createUrl(url), options).then(handleStatusCode);
2018-10-15 16:45:44 +02:00
}
delete(url: string): Promise<Response> {
let options: RequestOptions = {
method: "DELETE"
};
options = Object.assign(options, fetchOptions);
return fetch(createUrl(url), options).then(handleStatusCode);
}
httpRequestWithJSONBody(
2018-07-11 17:02:38 +02:00
method: string,
url: string,
contentType: string,
payload: any
): Promise<Response> {
let options: RequestOptions = {
method: method,
body: JSON.stringify(payload)
};
options = Object.assign(options, fetchOptions);
// $FlowFixMe
2018-07-11 17:02:38 +02:00
options.headers["Content-Type"] = contentType;
return fetch(createUrl(url), options).then(handleStatusCode);
}
}
export let apiClient = new ApiClient();