diff --git a/frontend/src/BinarisAPI.js b/frontend/src/BinarisAPI.js new file mode 100644 index 0000000..7b6f55f --- /dev/null +++ b/frontend/src/BinarisAPI.js @@ -0,0 +1,47 @@ +import urljoin from 'url-join'; + +function CORSOptions(itemData) { + const options = { + method: 'POST', + mode: 'cors', + }; + if (itemData) { + options.body = JSON.stringify(itemData); + options.headers = { 'Content-Type': 'application/json' }; + } + return options; +} + +class BinarisAPI { + constructor(rootEndpoint) { + this.createEndpoint = urljoin(rootEndpoint, 'public_create_endpoint'); + this.readEndpoint = urljoin(rootEndpoint, 'public_read_endpoint'); + this.updateEndpoint = urljoin(rootEndpoint, 'public_update_endpoint'); + this.deleteEndpoint = urljoin(rootEndpoint, 'public_delete_endpoint'); + } + + async createItem(item) { + const res = await fetch(this.createEndpoint, CORSOptions({ message: item })); + return res.json(); + } + + async readAllItems() { + const res = await fetch(this.readEndpoint, CORSOptions()); + return res.json(); + } + + async updateItem(itemID, item) { + const mergeData = { + message: item, + id: itemID, + }; + const res = await fetch(this.updateEndpoint, CORSOptions(mergeData)); + return res.json(); + } + + async deleteItem(itemID) { + await fetch(this.deleteEndpoint, CORSOptions({ id: itemID })); + } +} + +export default BinarisAPI; diff --git a/frontend/src/Todo.js b/frontend/src/Todo.js index 4335bc6..0e10e3d 100644 --- a/frontend/src/Todo.js +++ b/frontend/src/Todo.js @@ -1,34 +1,45 @@ import React, { Component } from 'react'; import Typography from '@material-ui/core/Typography'; -import uuidv4 from 'uuid/v4'; import './index.css'; import TodoList from './TodoList'; import TodoForm from './TodoForm'; +import BinarisAPI from './BinarisAPI'; + class Todo extends Component { constructor(props) { super(props); this.state = { todos: {} }; + if (!process.env.REACT_APP_BINARIS_ROOT_ENDPOINT) { + throw new Error('Environment variable "REACT_APP_BINARIS_ROOT_ENDPOINT" is required!'); + } + this.backend = new BinarisAPI(process.env.REACT_APP_BINARIS_ROOT_ENDPOINT); } createTodo = async todoText => { - const uniqueID = uuidv4(); + const newItemData = await this.backend.createItem(todoText); this.setState({ todos: { ...this.state.todos, - [uniqueID]: todoText, + ...newItemData, }, }); } removeTodo = async todoID => { + await this.backend.deleteItem(todoID); const todos = { ...this.state.todos }; delete todos[todoID]; this.setState({ todos }); } + async componentDidMount() { + const existingData = await this.backend.readAllItems(); + this.setState({ todos: existingData || {} }); + } + render() { return ( <div className="Todo">