Skip to content

Commit

Permalink
Refactor RestClient
Browse files Browse the repository at this point in the history
  Just extract all indy rest request into the RestClient to do a unified
  management
  • Loading branch information
ligangty committed Dec 18, 2023
1 parent 8a3da3c commit 21ffda0
Show file tree
Hide file tree
Showing 9 changed files with 210 additions and 68 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@

import React, {useState, useEffect} from 'react';
import {PropTypes} from 'prop-types';
import {jsonRest} from '#utils/RestClient.js';
import {IndyRest} from '#utils/RestClient.js';
import {Utils} from '#utils/AppUtils';

const {statsRes} = IndyRest;

export const PackageTypeSelect = ({register, formErrors}) =>{
const [state, setState] = useState({
pkgTypes: []
Expand All @@ -27,12 +29,12 @@ export const PackageTypeSelect = ({register, formErrors}) =>{

useEffect(()=>{
const fetchPkgTypes = async () =>{
const response = await jsonRest.get('/api/stats/package-type/keys');
if (response.ok){
const pkgTypes = await response.json();
const res = await statsRes.getAllPkgTypes();
if (res.success){
const pkgTypes = res.result;
setState({pkgTypes});
}else{
Utils.logMessage(response);
Utils.logMessage(res);
}
};
fetchPkgTypes();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,39 +19,39 @@ import {useNavigate} from 'react-router-dom';
// import {Modal} from 'bootstrap';
import {PropTypes} from 'prop-types';
import {Utils} from '#utils/AppUtils';
import {jsonRest,http, logErrors} from '#utils/RestClient';
import {IndyRest, logErrors} from '#utils/RestClient';
import {STORE_API_BASE_URL} from '../../ComponentConstants';
import {ChangeLogDialog, ConfirmDialog} from './PopupDialogs.jsx';

const {storeRes} = IndyRest;

const save = (store, mode, postSuccessHandler) => {
const saveUrl = `${STORE_API_BASE_URL}/${store.packageType}/${store.type}/${store.name}`;
const saveStore = async () => {
let response = {};
let res = {};
if(mode==="new"){
response = await jsonRest.post(saveUrl, store);
res = await storeRes.create(store);
}else if(mode ==="edit"){
response = await jsonRest.put(saveUrl, store);
res = await storeRes.update(store);
}
if (!response.ok){
if (!res.success){
// TODO: find another way to do error handling
logErrors(response);
Utils.logMessage(res.error.message);
}
if(response.status >= 200 || response.status < 300){
if(res.success){
postSuccessHandler(store);
}
};
saveStore();
};

const remove = (store, postHandler) => {
const deleteUrl = `${STORE_API_BASE_URL}/${store.packageType}/${store.type}/${store.name}`;
const removeStore = async ()=>{
const response = await http.delete(deleteUrl);
if(!response.ok && response.status >= 400){
const res = await storeRes.delete(store.packageType, store.type, store.name);
if(!res.success){
// TODO: Some other way to handle errors?
logErrors(response);
Utils.logMessage(res.error.message);
}
if(response.status===204){
if(res.success){
// TODO: Some other way to show deletion success?
Utils.logMessage("Store deleted.");
}
Expand Down
30 changes: 13 additions & 17 deletions src/main/webui/src/app/components/content/remote/RemoteEdit.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ import {PackageTypeSelect} from '../common/PackageTypeSelect.jsx';
// import ViewJsonDebugger from './Debugger.jsx';
import {Utils} from '#utils/AppUtils.js';
import {TimeUtils} from '#utils/TimeUtils.js';
import {jsonRest} from '#utils/RestClient.js';
import {STORE_API_BASE_URL, PATTERNS} from "../../ComponentConstants.js";
import {IndyRest} from '#utils/RestClient.js';
import {PATTERNS} from "../../ComponentConstants.js";

const {storeRes, disableRes} = IndyRest;

const CertificateSection = ({store, register}) => <div className="sub-fields">
{
Expand Down Expand Up @@ -87,33 +89,29 @@ export default function RemoteEdit() {

const path = location.pathname;
const mode = path.match(/.*\/new$/u)? 'new':'edit';
let [pkgType, storeName] = ["",""];
// Give a default packageType
let store = {"packageType": "maven", "type": "remote"};
[pkgType, storeName] = [packageType, name];
const storeAPIEndpoint = `${STORE_API_BASE_URL}/${pkgType}/remote/${storeName}`;
useEffect(()=>{
if(mode === 'edit'){
const fetchStore = async () =>{
// get Store data
const response = await jsonRest.get(storeAPIEndpoint);
if (response.ok){
const raw = await response.json();
const res = await storeRes.get(packageType, "remote", name);
if (res.success){
const raw = res.result;
const storeView = Utils.cloneObj(raw);
storeView.disabled = raw.disabled === undefined ? false : raw.disabled;
storeView.useX509 = raw.server_certificate_pem || raw.key_certificate_pem;
storeView.useProxy = raw.proxy_host && true;
// eslint-disable-next-line no-extra-parens
storeView.useAuth = (storeView.useProxy && storeView.proxy_user) || storeView.user;
// get Store disablement data
const timeoutUrl = `/api/admin/schedule/store/${storeView.packageType}/${storeView.type}/${storeView.name}/disable-timeout`;
const timeoutResponse = await jsonRest.get(timeoutUrl);
const timeoutRes = await disableRes.getStoreTimeout(store.packageType, store.type, store.name);
const cloned = Utils.cloneObj(storeView);
if (timeoutResponse.ok){
const timeout = await timeoutResponse.json();
if (timeoutRes.success){
const timeout = timeoutRes.result;
cloned.disableExpiration = timeout.expiration;
}else{
response.text().then(error=>Utils.logMessage(`disable timeout getting failed! Error reason: ${error}`));
Utils.logMessage(`disable timeout getting failed! Error reason: ${timeoutRes.error.message}`);
}
// Change state and re-rendering
setState({
Expand All @@ -126,15 +124,13 @@ export default function RemoteEdit() {
setUseX509(storeView.useX509);
}else{
// TODO: find another way to do error handling
response.text().then(error=>setState({
message: error
}));
Utils.logMessage(`Failed to get store data. Error reason: ${res.error.status}->${res.error.message}`);
}
};

fetchStore();
}
}, [storeAPIEndpoint, mode, reset]);
}, [packageType, name, mode, reset]);

if (mode === 'edit'){
store = state.store;
Expand Down
24 changes: 12 additions & 12 deletions src/main/webui/src/app/components/content/remote/RemoteList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ import {remoteOptionLegend as options, STORE_API_BASE_URL} from "../../Component
import {StoreListingWidget} from '../common/StoreListingWidget.jsx';
import {LoadingSpiner} from "../common/LoadingSpiner.jsx";
import {Utils} from '#utils/AppUtils.js';
import {jsonRest} from '#utils/RestClient.js';
import {IndyRest} from '#utils/RestClient.js';

const {storeRes, disableRes} = IndyRest;

const handlers = {
handleDebug: (event, setState) => {
Expand Down Expand Up @@ -58,17 +60,17 @@ export default function RemoteList() {
useEffect(()=>{
setLoading(true);
const fetchdData = async ()=>{
const response = await jsonRest.get(`${STORE_API_BASE_URL}/${packageType}/remote`);
if (response.ok){
const timeoutResponse = await jsonRest.get('/api/admin/schedule/store/all/disable-timeout');
const res = await storeRes.getStores(packageType, "remote");
if (res.success){
const timeoutRes = await disableRes.getAllStoreTimeout();
let disabledMap = {};
if (timeoutResponse.ok){
const timeoutData = await timeoutResponse.json();
if (timeoutRes.success){
const timeoutData = timeoutRes.result;
disabledMap = Utils.setDisableMap(timeoutData);
}else{
timeoutResponse.text().then(data=>Utils.logMessage(`disable timeout get failed in remote listing! Error reason: ${data}`));
Utils.logMessage(`disable timeout get failed in remote listing! Error reason: ${timeoutRes.error.message}`);
}
let data = await response.json();
let data = res.result;
if(typeof data === 'string'){
data = JSON.parse(data);
}
Expand All @@ -78,10 +80,8 @@ export default function RemoteList() {
disabledMap
});
}else{
response.text().then(data=>{
setState({
message: data
});
setState({
message: res.error.message
});
}
setLoading(false);
Expand Down
22 changes: 10 additions & 12 deletions src/main/webui/src/app/components/content/remote/RemoteView.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ import {LoadingSpiner} from '../common/LoadingSpiner.jsx';
import {Filters} from '#utils/Filters.js';
import {Utils} from '#utils/AppUtils.js';
import {TimeUtils} from '#utils/TimeUtils.js';
import {jsonRest} from '#utils/RestClient.js';
import {STORE_API_BASE_URL} from '../../ComponentConstants.js';
import {IndyRest} from '#utils/RestClient.js';

const {storeRes, disableRes} = IndyRest;

const RemoteAccessSection = ({store})=> <div className="fieldset">
<div className="detail-field">
Expand Down Expand Up @@ -162,9 +163,9 @@ export default function RemoteView() {
useEffect(()=>{
setLoading(true);
const fetchStore = async () => {
const response = await jsonRest.get(`${STORE_API_BASE_URL}/${packageType}/remote/${name}`);
if (response.ok){
const raw = await response.json();
const res = await storeRes.get(packageType, "remote",name);
if (res.success){
const raw = res.result;
const store = Utils.cloneObj(raw);
store.disabled = raw.disabled === undefined ? false : raw.disabled;
store.useX509 = raw.server_certificate_pem || raw.key_certificate_pem;
Expand All @@ -173,21 +174,18 @@ export default function RemoteView() {
store.useAuth = store.useAuth || store.user;

// get Store disablement data
const timeoutUrl = `/api/admin/schedule/store/${store.packageType}/${store.type}/${store.name}/disable-timeout`;
const timeoutResponse = await jsonRest.get(timeoutUrl);
const timeoutRes = await disableRes.getStoreTimeout(store.packageType, store.type, store.name);
const newStore = Utils.cloneObj(store);
if(timeoutResponse.ok){
const timeoutData = await timeoutResponse.json();
if(timeoutRes.success){
const timeoutData = timeoutRes.result;
newStore.disableExpiration = timeoutData.expiration;
}
// Change state and re-rendering
setState({
store: newStore
});
}else{
response.text().then(data => {
Utils.logMessage(`Failed to get store data. Error reason: ${response.status}->${data}`);
});
Utils.logMessage(`Failed to get store data. Error reason: ${res.error.status}->${res.error.message}`);
}
setLoading(false);
};
Expand Down
15 changes: 8 additions & 7 deletions src/main/webui/src/app/components/nav/NavFooter.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,25 @@
import React, {useEffect, useState} from 'react';
import Container from 'react-bootstrap/Container';
import Navbar from 'react-bootstrap/Navbar';
import {jsonRest} from '../../utils/RestClient';
import {IndyRest} from '../../utils/RestClient';
import {Utils} from '../../utils/AppUtils';
import {Col, Row} from 'react-bootstrap';

const {statsRes} = IndyRest;

export default function NavFooter() {
const [state, setState] = useState({stats: {}});

useEffect(()=>{
const fetchVersion = async () => {
const response = await jsonRest.get(`/api/stats/version-info`);
if (response.ok){
const raw = await response.json();
const res = await statsRes.getVersion();
if (res.success){
setState({
stats: raw
stats: res.result
});
}else{
response.text().then(data => {
Utils.logMessage(`Failed to version info. Error reason: ${response.status}->${data}`);
res.text().then(data => {
Utils.logMessage(`Failed to version info. Error reason: ${res.status}->${data}`);
});
}
};
Expand Down
27 changes: 26 additions & 1 deletion src/main/webui/src/app/utils/AppUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,5 +154,30 @@ export const Utils = {
}
}
}
}
},
sortEndpoints: endpoints => {
let typeOrder = ['group', 'remote', 'hosted'];
return endpoints.sort((a, b) => {
let ta = typeOrder.indexOf(a.type);
let tb = typeOrder.indexOf(b.type);

if (ta !== tb){
return ta < tb ? -1 : 1;
}

if (a.packageType < b.packageType){
return -1;
}else if (b.packageType < a.packageType){
return 1;
}

if (a.name < b.name){
return -1;
}else if (b.name < a.name){
return 1;
}

return 0;
});
},
};
Loading

0 comments on commit 21ffda0

Please sign in to comment.