Explorar el Código

extended baseApi to support endpoint gen for path params

jusrhee hace 5 años
padre
commit
5abe4e50e9

+ 1 - 1
dashboard/package.json

@@ -7,7 +7,7 @@
     "@testing-library/react": "^9.3.2",
     "@testing-library/react": "^9.3.2",
     "@testing-library/user-event": "^7.1.2",
     "@testing-library/user-event": "^7.1.2",
     "@types/jest": "^24.0.0",
     "@types/jest": "^24.0.0",
-    "@types/node": "^12.0.0",
+    "@types/node": "^12.12.62",
     "@types/react": "^16.9.49",
     "@types/react": "^16.9.49",
     "@types/react-dom": "^16.9.8",
     "@types/react-dom": "^16.9.8",
     "@types/react-modal": "^3.10.6",
     "@types/react-modal": "^3.10.6",

+ 4 - 3
dashboard/src/main/Login.tsx

@@ -36,12 +36,13 @@ export default class Login extends Component<PropsType, StateType> {
     } else {
     } else {
       
       
       // Attempt user login
       // Attempt user login
-      api.logInUser('', {
+      api.logInUser('<token>', {
         email: email,
         email: email,
         password: password
         password: password
-      }, (err, res) => {
+      }, (err: any, res: any) => {
         // TODO: case and set credential error
         // TODO: case and set credential error
-        
+
+        console.log(err)
         err ? setCurrentError(JSON.stringify(err)) : authenticate();
         err ? setCurrentError(JSON.stringify(err)) : authenticate();
       });
       });
     }
     }

+ 1 - 1
dashboard/src/main/Register.tsx

@@ -47,7 +47,7 @@ export default class Register extends Component<PropsType, StateType> {
       api.registerUser('', {
       api.registerUser('', {
         email: email,
         email: email,
         password: password
         password: password
-      }, (err, res) => {
+      }, (err: any, res: any) => {
         err ? setCurrentError(JSON.stringify(err)) : authenticate();
         err ? setCurrentError(JSON.stringify(err)) : authenticate();
       });
       });
     } 
     } 

+ 5 - 1
dashboard/src/main/home/sidebar/ClusterSection.tsx

@@ -20,11 +20,15 @@ export default class ClusterSection extends Component<PropsType, StateType> {
 
 
   // Need to track initialized for animation mounting
   // Need to track initialized for animation mounting
   state = {
   state = {
-    configExists: true,
+    configExists: false,
     showDrawer: false,
     showDrawer: false,
     initializedDrawer: false,
     initializedDrawer: false,
   };
   };
 
 
+  componentDidMount() {
+    // TODO: Check if
+  }
+
   // Need to override showDrawer when the sidebar is closed
   // Need to override showDrawer when the sidebar is closed
   componentDidUpdate(prevProps: PropsType) {
   componentDidUpdate(prevProps: PropsType) {
     if (prevProps !== this.props) {
     if (prevProps !== this.props) {

+ 18 - 1
dashboard/src/main/home/sidebar/Sidebar.tsx

@@ -2,6 +2,9 @@ import React, { Component } from 'react';
 import styled from 'styled-components';
 import styled from 'styled-components';
 import gradient from '../../../assets/grad.jpg';
 import gradient from '../../../assets/grad.jpg';
 
 
+import api from '../../../shared/api';
+import { Context } from '../../../shared/Context';
+
 import ClusterSection from './ClusterSection';
 import ClusterSection from './ClusterSection';
 
 
 type PropsType = {
 type PropsType = {
@@ -73,6 +76,18 @@ export default class Sidebar extends Component<PropsType, StateType> {
     }
     }
   };
   };
 
 
+  handleLogout = (): void => {
+    let { logOut } = this.props;
+    let { setCurrentError } = this.context;
+
+    // Attempt user logout
+    api.logOutUser('<token>', {}, (err, res) => {
+      // TODO: case and set logout error
+      
+      err ? setCurrentError(JSON.stringify(err)) : logOut();
+    });
+  }
+
   // SidebarBg is separate to cover retracted drawer
   // SidebarBg is separate to cover retracted drawer
   render() {
   render() {
     return (
     return (
@@ -102,7 +117,7 @@ export default class Sidebar extends Component<PropsType, StateType> {
             releaseDrawer={() => this.setState({ forceCloseDrawer: false })}
             releaseDrawer={() => this.setState({ forceCloseDrawer: false })}
           />
           />
 
 
-          <LogOutButton onClick={this.props.logOut}>
+          <LogOutButton onClick={this.handleLogout}>
             Log Out <i className="material-icons">keyboard_return</i>
             Log Out <i className="material-icons">keyboard_return</i>
           </LogOutButton>
           </LogOutButton>
         </StyledSidebar>
         </StyledSidebar>
@@ -111,6 +126,8 @@ export default class Sidebar extends Component<PropsType, StateType> {
   }
   }
 }
 }
 
 
+Sidebar.contextType = Context;
+
 const NavButton = styled.div`
 const NavButton = styled.div`
   display: block;
   display: block;
   position: relative;
   position: relative;

+ 10 - 1
dashboard/src/shared/api.tsx

@@ -1,8 +1,17 @@
+import axios from 'axios';
 import { baseApi } from './baseApi';
 import { baseApi } from './baseApi';
 
 
+/**
+ * Generic api call format
+ * @param {string} token - Bearer token.
+ * @param {Object} params - Query params.
+ * @param {Object} pathParams - Path params.
+ * @param {(err: Object, res: Object) => void} callback - Callback function.
+ */
+
 const registerUser = baseApi<{ 
 const registerUser = baseApi<{ 
   email: string, 
   email: string, 
-  password: string 
+  password: string
 }>('POST', '/api/register');
 }>('POST', '/api/register');
 
 
 const logInUser = baseApi<{
 const logInUser = baseApi<{

+ 40 - 20
dashboard/src/shared/baseApi.tsx

@@ -1,10 +1,32 @@
 import axios from 'axios';
 import axios from 'axios';
 
 
 // Partial function that accepts a generic params type and returns an api method
 // Partial function that accepts a generic params type and returns an api method
-export const baseApi = <T extends {}>(requestType: string, endpoint: string) => {
-  if (requestType === 'POST') {
-    return (token: string, params?: T, callback?: (err: any, res: any) => void) => {
-      axios.post(`https://${process.env.API_SERVER + endpoint}`, params, {
+export const baseApi = <T extends {}, S = {}>(requestType: string, endpoint: ((pathParams?: S) => string) | string) => {
+  return (token: string, params: T, callback?: (err: any, res: any) => void) => {
+
+    // Generate endpoint literal
+    let endpointString: ((pathParams: S) => string) | string;
+    if (typeof endpoint === 'string') {
+      endpointString = endpoint;
+    } else {
+      endpointString = 'fuck'
+    }
+
+    // Handle request type (can refactor)
+    if (requestType === 'POST') {
+      axios.post(`https://${(process as any).env.API_SERVER + endpointString}`, params, {
+        headers: {
+          Authorization: `Bearer ${token}`
+        }
+      })
+      .then(res => {
+        callback && callback(null, res.data);
+      })
+      .catch(err => {
+        callback && callback(err, null);
+      });
+    } else if (requestType === 'PUT') {
+      axios.put(`https://${(process as any).env.API_SERVER + endpointString}`, params, {
         headers: {
         headers: {
           Authorization: `Bearer ${token}`
           Authorization: `Bearer ${token}`
         }
         }
@@ -15,21 +37,19 @@ export const baseApi = <T extends {}>(requestType: string, endpoint: string) =>
       .catch(err => {
       .catch(err => {
         callback && callback(err, null);
         callback && callback(err, null);
       });
       });
-    };
+    } else {
+      axios.get(`https://${(process as any).env.API_SERVER + endpoint}`, {
+        headers: {
+          Authorization: `Bearer ${token}`
+        },
+        params
+      })
+      .then(res => {
+        callback && callback(null, res.data);
+      })
+      .catch(err => {
+        callback && callback(err, null);
+      });
+    }
   }
   }
-
-  return (token: string, params?: T, callback?: (err: any, res: any) => void) => {
-    axios.get(`https://${process.env.API_SERVER + endpoint}`, {
-      headers: {
-        Authorization: `Bearer ${token}`
-      },
-      params
-    })
-    .then(res => {
-      callback && callback(null, res.data);
-    })
-    .catch(err => {
-      callback && callback(err, null);
-    });
-  };
 }
 }