Переглянути джерело

init work on server api and frontend requests

Ivan Galakhov 4 роки тому
батько
коміт
300a04aee0

+ 15 - 10
dashboard/src/components/Button.tsx

@@ -1,14 +1,19 @@
-import React from 'react';
+import React from "react";
 import styled from "styled-components";
 
 interface Props {
-  disabled?: boolean
-  children: React.ReactNode
+  disabled?: boolean;
+  children: React.ReactNode;
+  onClick: () => void;
 }
 
-const Button = ({children, disabled} : Props) => {
-    return <ButtonWrapper disabled={disabled}>{children}</ButtonWrapper>
-}
+const Button = ({ children, disabled, onClick }: Props) => {
+  return (
+    <ButtonWrapper disabled={disabled} onClick={onClick}>
+      {children}
+    </ButtonWrapper>
+  );
+};
 
 export default Button;
 
@@ -28,13 +33,13 @@ const ButtonWrapper = styled.div`
   text-overflow: ellipsis;
   box-shadow: 0 5px 8px 0px #00000010;
   cursor: ${(props: { disabled?: boolean }) =>
-  props.disabled ? "not-allowed" : "pointer"};
+    props.disabled ? "not-allowed" : "pointer"};
 
   background: ${(props: { disabled?: boolean }) =>
-  props.disabled ? "#aaaabbee" : "#616FEEcc"};
+    props.disabled ? "#aaaabbee" : "#616FEEcc"};
   :hover {
     background: ${(props: { disabled?: boolean }) =>
-  props.disabled ? "" : "#505edddd"};
+      props.disabled ? "" : "#505edddd"};
   }
 
   > i {
@@ -49,4 +54,4 @@ const ButtonWrapper = styled.div`
     margin-right: 5px;
     justify-content: center;
   }
-`;
+`;

+ 134 - 103
dashboard/src/components/repo-selector/RepoList.tsx

@@ -1,4 +1,4 @@
-import React, { useState, useContext, useEffect } from "react";
+import React, { useState, useContext, useEffect, useRef } from "react";
 import styled from "styled-components";
 import github from "assets/github.png";
 
@@ -8,6 +8,7 @@ import { Context } from "shared/Context";
 
 import Loading from "../Loading";
 import Button from "../Button";
+import { AxiosResponse } from "axios";
 
 type Props = {
   actionConfig: ActionConfigType | null;
@@ -26,122 +27,137 @@ const RepoList = ({
   const [loading, setLoading] = useState(true);
   const [error, setError] = useState(false);
   const [searchFilter, setSearchFilter] = useState("");
+  const gitReposIDs = useRef<[number]>(null);
   const { currentProject } = useContext(Context);
 
   // TODO: Try to unhook before unmount
   useEffect(() => {
-    // Get repos
+    // load git repo ids, only need to do this once through component lifecycle
+
     if (!userId && userId !== 0) {
       api
         .getGitRepos("<token>", {}, { project_id: currentProject.id })
         .then(async (res) => {
-          if (res.data.length == 0) {
-            setLoading(false);
-            setError(false);
-            return;
-          }
-
-          var allRepos: any = [];
-          var errors: any = [];
-
-          console.log(res);
-
-          var promises = res.data.map((gitrepo: any, id: number) => {
-            return new Promise((resolve, reject) => {
-              api
-                .getGitRepoList(
-                  "<token>",
-                  {},
-                  { project_id: currentProject.id, git_repo_id: gitrepo.id }
-                )
-                .then((res) => {
-                  res.data.forEach((repo: any, id: number) => {
-                    repo.GHRepoID = gitrepo.id;
-                  });
-
-                  resolve(res.data);
-                })
-                .catch((err) => {
-                  errors.push(err);
-                  resolve([]);
-                });
-            });
-          });
-
-          var sepRepos = await Promise.all(promises);
-
-          allRepos = [].concat.apply([], sepRepos);
-
-          // remove duplicates based on name
-          allRepos = allRepos.filter((repo: any, index: number, self: any) => {
-            var keep =
-              index ===
-              self.findIndex((_repo: any) => {
-                return repo.FullName === _repo.FullName;
-              });
-
-            return keep;
-          });
-
-          // sort repos based on name
-          allRepos.sort((a: any, b: any) => {
-            if (a.FullName < b.FullName) {
-              return -1;
-            } else if (a.FullName > b.FullName) {
-              return 1;
-            } else {
-              return 0;
-            }
-          });
-
-          if (allRepos.length == 0 && errors.length > 0) {
-            setLoading(false);
-            setError(true);
-          } else {
-            setRepos(allRepos);
-            setLoading(false);
-            setError(false);
-          }
+          gitReposIDs.current = res.data.map((gitrepo: any) => gitrepo.id);
         })
         .catch((_) => {
           setLoading(false);
           setError(true);
         });
     } else {
-      // ??? wouldn't this always be an undefined request?
-      let grid = userId;
-
-      api
-        .getGitRepoList(
-          "<token>",
-          {},
-          { project_id: currentProject.id, git_repo_id: grid }
-        )
-        .then((res) => {
-          var repos: any = res.data;
-
-          repos.forEach((repo: any, id: number) => {
-            repo.GHRepoID = grid;
-          });
-
-          repos.sort((a: any, b: any) => {
-            if (a.FullName < b.FullName) {
-              return -1;
-            } else if (a.FullName > b.FullName) {
-              return 1;
-            } else {
-              return 0;
-            }
-          });
-          setRepos(repos);
-          setLoading(false);
-          setError(false);
-        })
-        .catch((_) => {
-          setLoading(false);
-          setError(true);
-        });
+      gitReposIDs.current = [userId];
     }
+
+    // if (!userId && userId !== 0) {
+    //   api
+    //     .getGitRepos("<token>", {}, { project_id: currentProject.id })
+    //     .then(async (res) => {
+    //       if (res.data.length == 0) {
+    //         setLoading(false);
+    //         setError(false);
+    //         return;
+    //       }
+    //
+    //       var allRepos: any = [];
+    //       var errors: any = [];
+    //
+    //       console.log(res);
+    //
+    //       var promises = res.data.map((gitrepo: any, id: number) => {
+    //         return new Promise((resolve, reject) => {
+    //           api
+    //             .getGitRepoList(
+    //               "<token>",
+    //               {},
+    //               { project_id: currentProject.id, git_repo_id: gitrepo.id }
+    //             )
+    //             .then((res) => {
+    //               res.data.forEach((repo: any, id: number) => {
+    //                 repo.GHRepoID = gitrepo.id;
+    //               });
+    //
+    //               resolve(res.data);
+    //             })
+    //             .catch((err) => {
+    //               errors.push(err);
+    //               resolve([]);
+    //             });
+    //         });
+    //       });
+    //
+    //       var sepRepos = await Promise.all(promises);
+    //
+    //       allRepos = [].concat.apply([], sepRepos);
+    //
+    //       // remove duplicates based on name
+    //       allRepos = allRepos.filter((repo: any, index: number, self: any) => {
+    //         var keep =
+    //           index ===
+    //           self.findIndex((_repo: any) => {
+    //             return repo.FullName === _repo.FullName;
+    //           });
+    //
+    //         return keep;
+    //       });
+    //
+    //       // sort repos based on name
+    //       allRepos.sort((a: any, b: any) => {
+    //         if (a.FullName < b.FullName) {
+    //           return -1;
+    //         } else if (a.FullName > b.FullName) {
+    //           return 1;
+    //         } else {
+    //           return 0;
+    //         }
+    //       });
+    //
+    //       if (allRepos.length == 0 && errors.length > 0) {
+    //         setLoading(false);
+    //         setError(true);
+    //       } else {
+    //         setRepos(allRepos);
+    //         setLoading(false);
+    //         setError(false);
+    //       }
+    //     })
+    //     .catch((_) => {
+    //       setLoading(false);
+    //       setError(true);
+    //     });
+    // } else {
+    //   let grid = userId;
+    //
+    //   api
+    //     .getGitRepoList(
+    //       "<token>",
+    //       {},
+    //       { project_id: currentProject.id, git_repo_id: grid }
+    //     )
+    //     .then((res) => {
+    //       var repos: any = res.data;
+    //
+    //       repos.forEach((repo: any, id: number) => {
+    //         repo.GHRepoID = grid;
+    //       });
+    //
+    //       repos.sort((a: any, b: any) => {
+    //         if (a.FullName < b.FullName) {
+    //           return -1;
+    //         } else if (a.FullName > b.FullName) {
+    //           return 1;
+    //         } else {
+    //           return 0;
+    //         }
+    //       });
+    //       setRepos(repos);
+    //       setLoading(false);
+    //       setError(false);
+    //     })
+    //     .catch((_) => {
+    //       setLoading(false);
+    //       setError(true);
+    //     });
+    // }
   }, []);
 
   const setRepo = (x: RepoType) => {
@@ -194,6 +210,16 @@ const RepoList = ({
       });
   };
 
+  const updateSearchResults = () => {
+    setLoading(true);
+
+    // api.
+    //   .searchGitRepos("<token>", {}, { project_id: currentProject.id })
+    //   .then((res: AxiosResponse) => {
+    //     console.log(res);
+    //   });
+  };
+
   const renderExpanded = () => {
     if (readOnly) {
       return <ExpandedWrapperAlt>{renderRepoList()}</ExpandedWrapperAlt>;
@@ -211,7 +237,12 @@ const RepoList = ({
                 placeholder="Search repos..."
               />
             </SearchBar>
-            <Button>Search</Button>
+            <Button
+              onClick={updateSearchResults}
+              disabled={!searchFilter || !/\S/.test(searchFilter) || loading}
+            >
+              Search
+            </Button>
           </SearchRow>
           <ExpandedWrapper>
             <ExpandedWrapper>{renderRepoList()}</ExpandedWrapper>

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

@@ -389,6 +389,15 @@ const getClusters = baseApi<{}, { id: number }>("GET", (pathParams) => {
   return `/api/projects/${pathParams.id}/clusters`;
 });
 
+const searchGitRepos = baseApi<
+  {},
+  {
+    project_id: number;
+  }
+>("GET", (pathParams) => {
+  return `/api/projects/${pathParams.project_id}/gitrepos/search`;
+});
+
 const getGitRepoList = baseApi<
   {},
   {
@@ -847,6 +856,7 @@ export default {
   getClusterIntegrations,
   getClusters,
   getConfigMap,
+  searchGitRepos,
   getGitRepoList,
   getGitRepos,
   getImageRepos,

+ 12 - 0
server/api/git_repo_handler.go

@@ -59,6 +59,18 @@ type DirectoryItem struct {
 	Type string
 }
 
+// HandleSearchRepos searches user repos
+func (app *App) HandleSearchRepos(w http.ResponseWriter, r *http.Request) {
+	tok, err := app.githubTokenFromRequest(r)
+
+	if err != nil {
+		app.handleErrorInternal(err, w)
+		return
+	}
+
+	json.NewEncoder(w).Encode(tok)
+}
+
 // HandleListRepos retrieves a list of repo names
 func (app *App) HandleListRepos(w http.ResponseWriter, r *http.Request) {
 	tok, err := app.githubTokenFromRequest(r)

+ 14 - 0
server/router/router.go

@@ -1000,6 +1000,20 @@ func New(a *api.App) *chi.Mux {
 				),
 			)
 
+			r.Method(
+				"GET",
+				"/projects/{project_id}/gitrepos/{git_repo_id}/search",
+				auth.DoesUserHaveProjectAccess(
+					auth.DoesUserHaveGitRepoAccess(
+						requestlog.NewHandler(a.HandleListRepos, l),
+						mw.URLParam,
+						mw.URLParam,
+					),
+					mw.URLParam,
+					mw.ReadAccess,
+				),
+			)
+
 			r.Method(
 				"GET",
 				"/projects/{project_id}/gitrepos/{git_repo_id}/repos",