Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/user frontend #99

Open
wants to merge 11 commits into
base: dev
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
add api setup
  • Loading branch information
Philipp Doll committed Sep 24, 2021
commit defdf738d2830b07a911d283ba0bf0c095083ade
3 changes: 3 additions & 0 deletions src/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
apiUrl: 'http://localhost:3000/api/v1'
}
140 changes: 140 additions & 0 deletions src/users_api/BaseAPI.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import Config from '../config/index';

export interface RequestOptions {
config: { apiUrl: string };
fetchFunc: typeof window.fetch;
}

class ResponseError extends Error {
public response?: Response;
public body: any;
}

export const corsFetchOptions: {
mode: RequestMode;
} = {
mode: 'cors',
};

export const acceptJsonHeaders = {
Accept: 'application/json'
};

export const contentTypeJsonHeaders = {
'Content-Type': 'application/json; charset=utf-8'
};

export const contentTypeFormUrlEncodedHeaders = {
'Content-Type': 'application/x-www-form-urlencoded'
};

const checkStatus = async (response: Response) => {
if (!response.ok) {
const error = new ResponseError(
`${response.status} ${response.statusText}`
);
error.response = response;
// Try to parse the response body as JSON.
let body;
try {
body = await response.json();
} catch (e) {
// parsing the error response to json failed
// Reject the new promise
throw error;
}
// parsing the error response was succuess
// Add body property to error
error.body = body;
// Reject the new promise
throw error;
}
return response;
};

const parseJson = <T>(response: Response): T | Promise<T> =>
response.status === 204 ? ({} as T) : response.json();

export const get = async <T>(url: string, options?: RequestOptions) => {
const mergedOptions: RequestOptions = {
config: Config,
fetchFunc: fetch,
...options
};
const { config, fetchFunc } = mergedOptions;

const headers = {
...acceptJsonHeaders
};

const fetchOptions = {
...corsFetchOptions,
method: 'GET',
headers
};
const finalUrl = `${config.apiUrl}${url}`;

const response = await fetchFunc(finalUrl, fetchOptions);
const checkedResponse = await checkStatus(response);
return parseJson<T>(checkedResponse);
};

const requestWithBody = async <T>(
method: string,
url: string,
data: any,
options?: RequestOptions
) => {
const mergedOptions: RequestOptions = {
config: Config,
fetchFunc: fetch,
...options
};
const { config, fetchFunc } = mergedOptions;

// process different data types
let body: string;
let headers: { [key: string]: string };
if (typeof data === 'string') {
headers = {
...acceptJsonHeaders,
...contentTypeFormUrlEncodedHeaders
};
body = data;
} else {
headers = {
...acceptJsonHeaders,
...contentTypeJsonHeaders
};
body = JSON.stringify(data);
}

const fetchOptions = {
...corsFetchOptions,
method,
headers,
body
};

const finalUrl = `${config.apiUrl}${url}`;

// this is the browser actually doing the fetch
const response = await fetchFunc(finalUrl, fetchOptions);
const checkedResponse = await checkStatus(response);
return parseJson<T>(checkedResponse);
};

export const post = <T>(url: string, data: any, options?: RequestOptions) =>
requestWithBody<T>('POST', url, data, options);

export const put = <T>(url: string, data: any, options?: RequestOptions) =>
requestWithBody<T>('PUT', url, data, options);

export const patch = <T>(url: string, data: any, options?: RequestOptions) =>
requestWithBody<T>('PATCH', url, data, options);

/**
* Makes a DELETE request. Is called destroy because delete is a JavaScript keyword.
*/
export const destroy = <T>(url: string, data?: any, options?: RequestOptions) =>
requestWithBody<T>('DELETE', url, data, options);
19 changes: 19 additions & 0 deletions src/users_api/UserAPI.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { destroy, get, patch, post } from './BaseAPI';

const uri = encodeURIComponent;

export const getUser = (id: number) => {
return get('/users/' + uri(id))
}

export const updateUser = (id: number, data: any) => {
return patch('/users/' + uri(id), {
user: data
})
}

export const createUser = (data: any) => {
return post('/users/', {
user: data
})
}