Skip to content

Commit

Permalink
connect everything
Browse files Browse the repository at this point in the history
  • Loading branch information
rylandg committed Jan 31, 2019
1 parent 470b4c6 commit 0814f02
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 3 deletions.
47 changes: 47 additions & 0 deletions frontend/src/BinarisAPI.js
Original file line number Diff line number Diff line change
@@ -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;
17 changes: 14 additions & 3 deletions frontend/src/Todo.js
Original file line number Diff line number Diff line change
@@ -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">
Expand Down

0 comments on commit 0814f02

Please sign in to comment.