mirror of
https://bitbucket.org/wisemapping/wisemapping-frontend.git
synced 2024-11-10 17:33:24 +01:00
Split Client into two classes.
This commit is contained in:
parent
a45d18aebc
commit
8df40788ba
@ -32,6 +32,51 @@ export type ErrorInfo = {
|
||||
fields?: Map<String, String>;
|
||||
}
|
||||
|
||||
export const parseResponseOnError = (response: any): ErrorInfo => {
|
||||
|
||||
let result: ErrorInfo | undefined;
|
||||
if (response) {
|
||||
const status: number = response.status;
|
||||
const data = response.data;
|
||||
console.log(data);
|
||||
|
||||
switch (status) {
|
||||
case 401:
|
||||
// this.authFailed();
|
||||
break;
|
||||
default:
|
||||
if (data) {
|
||||
// Set global errors ...
|
||||
if (data.globalErrors) {
|
||||
let msg;
|
||||
let errors = data.globalErrors;
|
||||
if (errors.length > 0) {
|
||||
msg = errors[0];
|
||||
}
|
||||
result = { msg: errors };
|
||||
}
|
||||
|
||||
// Set field errors ...
|
||||
if (data.fieldErrors) {
|
||||
// @Todo: Fix this ...
|
||||
result = { msg: data.fieldErrors };
|
||||
result.fields = new Map<string, string>();
|
||||
}
|
||||
|
||||
} else {
|
||||
result = { msg: response.statusText };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Network related problem ...
|
||||
if (!result) {
|
||||
result = { msg: 'Unexpected error. Please, try latter' };
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
interface Client {
|
||||
createMap(rest: { name: string; description?: string | undefined })
|
||||
deleteLabel(label: string): Promise<unknown>;
|
||||
@ -44,6 +89,7 @@ interface Client {
|
||||
duplicateMap(id: number, basicInfo: BasicMapInfo): Promise<void>;
|
||||
loadMapInfo(id: number): Promise<BasicMapInfo>;
|
||||
changeStarred(id: number): Promise<void>;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,15 +1,11 @@
|
||||
import { BasicMapInfo, ErrorInfo, MapInfo, NewUser } from "..";
|
||||
import Client from "..";
|
||||
import Client, { BasicMapInfo, ErrorInfo, MapInfo, NewUser, parseResponseOnError } from '..';
|
||||
import axios from "axios";
|
||||
|
||||
class MockClient implements Client {
|
||||
private baseUrl: string;
|
||||
private authFailed: () => void
|
||||
private maps: MapInfo[] = [];
|
||||
private labels: string[] = [];
|
||||
|
||||
constructor(baseUrl: string, authFailed: () => void) {
|
||||
this.baseUrl = baseUrl;
|
||||
constructor() {
|
||||
|
||||
// Remove, just for develop ....
|
||||
function createMapInfo(
|
||||
@ -138,20 +134,7 @@ s
|
||||
}
|
||||
|
||||
registerNewUser(user: NewUser): Promise<void> {
|
||||
const handler = (success: () => void, reject: (error: ErrorInfo) => void) => {
|
||||
axios.post(this.baseUrl + '/service/users',
|
||||
JSON.stringify(user),
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
).then(response => {
|
||||
// All was ok, let's sent to success page ...;
|
||||
success();
|
||||
}).catch(error => {
|
||||
const response = error.response;
|
||||
const errorInfo = this.parseResponseOnError(response);
|
||||
reject(errorInfo);
|
||||
});
|
||||
}
|
||||
return new Promise(handler);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
fetchAllMaps(): Promise<MapInfo[]> {
|
||||
@ -160,66 +143,7 @@ s
|
||||
}
|
||||
|
||||
resetPassword(email: string): Promise<void> {
|
||||
|
||||
const handler = (success: () => void, reject: (error: ErrorInfo) => void) => {
|
||||
axios.post(`${this.baseUrl}/service/users/resetPassword?email=${email}`,
|
||||
null,
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
).then(response => {
|
||||
// All was ok, let's sent to success page ...;
|
||||
success();
|
||||
}).catch(error => {
|
||||
const response = error.response;
|
||||
const errorInfo = this.parseResponseOnError(response);
|
||||
reject(errorInfo);
|
||||
});
|
||||
}
|
||||
return new Promise(handler);
|
||||
}
|
||||
|
||||
private parseResponseOnError = (response: any): ErrorInfo => {
|
||||
|
||||
let result: ErrorInfo | undefined;
|
||||
if (response) {
|
||||
const status: number = response.status;
|
||||
const data = response.data;
|
||||
console.log(data);
|
||||
|
||||
switch (status) {
|
||||
case 401:
|
||||
this.authFailed();
|
||||
break;
|
||||
default:
|
||||
if (data) {
|
||||
// Set global errors ...
|
||||
if (data.globalErrors) {
|
||||
let msg;
|
||||
let errors = data.globalErrors;
|
||||
if (errors.length > 0) {
|
||||
msg = errors[0];
|
||||
}
|
||||
result = { msg: errors };
|
||||
}
|
||||
|
||||
// Set field errors ...
|
||||
if (data.fieldErrors) {
|
||||
// @Todo: Fix this ...
|
||||
result = { msg: data.fieldErrors };
|
||||
result.fields = new Map<string, string>();
|
||||
}
|
||||
|
||||
} else {
|
||||
result = { msg: response.statusText };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Network related problem ...
|
||||
if (!result) {
|
||||
result = { msg: 'Unexpected error. Please, try latter' };
|
||||
}
|
||||
|
||||
return result;
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
|
54
packages/webapp/src/client/rest-client/index.ts
Normal file
54
packages/webapp/src/client/rest-client/index.ts
Normal file
@ -0,0 +1,54 @@
|
||||
import axios from 'axios';
|
||||
import { ErrorInfo, MapInfo, NewUser, parseResponseOnError } from '..';
|
||||
import MockClient from '../mock-client/';
|
||||
|
||||
//@Remove inheritance once is it completed.
|
||||
export default class RestClient extends MockClient {
|
||||
private baseUrl: string;
|
||||
private authFailed: () => void
|
||||
|
||||
constructor(baseUrl: string, authFailed: () => void) {
|
||||
super();
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
fetchAllMaps(): Promise<MapInfo[]> {
|
||||
console.log("Fetching maps from server")
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
registerNewUser(user: NewUser): Promise<void> {
|
||||
const handler = (success: () => void, reject: (error: ErrorInfo) => void) => {
|
||||
axios.post(this.baseUrl + '/service/users',
|
||||
JSON.stringify(user),
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
).then(response => {
|
||||
// All was ok, let's sent to success page ...;
|
||||
success();
|
||||
}).catch(error => {
|
||||
const response = error.response;
|
||||
const errorInfo = parseResponseOnError(response);
|
||||
reject(errorInfo);
|
||||
});
|
||||
}
|
||||
return new Promise(handler);
|
||||
}
|
||||
resetPassword(email: string): Promise<void> {
|
||||
|
||||
const handler = (success: () => void, reject: (error: ErrorInfo) => void) => {
|
||||
axios.put(`${this.baseUrl}/service/users/resetPassword?email=${email}`,
|
||||
null,
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
).then(response => {
|
||||
// All was ok, let's sent to success page ...;
|
||||
success();
|
||||
}).catch(error => {
|
||||
const response = error.response;
|
||||
const errorInfo = parseResponseOnError(response);
|
||||
reject(errorInfo);
|
||||
});
|
||||
}
|
||||
return new Promise(handler);
|
||||
}
|
||||
}
|
||||
|
@ -393,9 +393,9 @@ export const MapsList = (props: MapsListProps) => {
|
||||
|
||||
<TableBody>
|
||||
{isLoading ? (
|
||||
<TableRow><TableCell rowSpan={6}>Loading ...</TableCell></TableRow>) :
|
||||
<TableRow><TableCell colSpan={6}>Loading ...</TableCell></TableRow>) :
|
||||
(mapsInfo.length == 0 ?
|
||||
(<TableRow><TableCell rowSpan={6}>No matching records found</TableCell></TableRow>) :
|
||||
(<TableRow><TableCell colSpan={6} style={{textAlign:'center'}}><FormattedMessage id="maps.emptyresult" defaultMessage="No matching record found with the current filter criteria." /></TableCell></TableRow>) :
|
||||
stableSort(mapsInfo, getComparator(order, orderBy))
|
||||
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
|
||||
.map((row: MapInfo) => {
|
||||
|
@ -2,43 +2,46 @@ import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
import axios from 'axios';
|
||||
import Client from '../client';
|
||||
import MockClient from '../client/mock-client';
|
||||
import RestClient from '../client/rest-client';
|
||||
|
||||
type RutimeConfig = {
|
||||
apiBaseUrl: string;
|
||||
interface ConfigInfo {
|
||||
apiBaseUrl: string
|
||||
}
|
||||
|
||||
async function loadRuntimeConfig() {
|
||||
let result: RutimeConfig | undefined;
|
||||
class RutimeConfig {
|
||||
private config: ConfigInfo;
|
||||
|
||||
await axios.get("runtime-config.json"
|
||||
).then(response => {
|
||||
// All was ok, let's sent to success page ...
|
||||
result = response.data as RutimeConfig;
|
||||
console.log("Dynamic configuration->" + response.data);
|
||||
}).catch(e => {
|
||||
console.log(e)
|
||||
});
|
||||
constructor() {
|
||||
|
||||
if (!result) {
|
||||
// Ok, try to create a default configuration relative to the current path ...
|
||||
console.log("Configuration could not be loaded, falback to default config.")
|
||||
const location = window.location;
|
||||
const basePath = location.protocol + "//" + location.host + "/" + location.pathname.split('/')[1]
|
||||
|
||||
result = {
|
||||
apiBaseUrl: basePath
|
||||
}
|
||||
|
||||
load() {
|
||||
|
||||
// Config can be inserted in the html page to define the global properties ...
|
||||
this.config = (window as any).serverconfig;
|
||||
return this;
|
||||
}
|
||||
|
||||
buildClient(): Client {
|
||||
let result: Client;
|
||||
if (this.config) {
|
||||
result = new RestClient(this.config.apiBaseUrl, () => { console.log("401 error") });
|
||||
console.log("Service using rest client. " + JSON.stringify(this.config))
|
||||
|
||||
} else {
|
||||
console.log("Warning:Service using mockservice client")
|
||||
result = new MockClient();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
interface ServiceState {
|
||||
instance: Client;
|
||||
}
|
||||
|
||||
const initialState: ServiceState = {
|
||||
instance: new MockClient("", () => { console.log("401 error") })
|
||||
instance: new RutimeConfig().load().buildClient()
|
||||
};
|
||||
|
||||
export const serviceSlice = createSlice({
|
||||
@ -46,7 +49,7 @@ export const serviceSlice = createSlice({
|
||||
initialState: initialState,
|
||||
reducers: {
|
||||
initialize(state, action: PayloadAction<void[]>) {
|
||||
state.instance = new MockClient("", () => { console.log("401 error") });
|
||||
// state.instance = new RutimeConfig().load().buildClient()
|
||||
}
|
||||
},
|
||||
});
|
||||
@ -54,5 +57,6 @@ export const serviceSlice = createSlice({
|
||||
export const activeInstance = (state: any): Client => {
|
||||
return state.service.instance;
|
||||
}
|
||||
|
||||
export default serviceSlice.reducer
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user