[DEV] remove all async it is too slow...

This commit is contained in:
Edouard DUPIN 2024-08-29 20:09:59 +02:00
parent d49e1d06fe
commit 244f8a988e
10 changed files with 255 additions and 379 deletions

View File

@ -4,153 +4,169 @@
* @license PROPRIETARY (see license file)
*/
import { Injectable } from '@angular/core';
import { Injectable } from "@angular/core";
import { Album, AlbumResource, UUID } from 'app/back-api';
import { RESTConfig } from 'app/back-api/rest-tools';
import { environment } from 'environments/environment';
import { GenericDataService } from './GenericDataService';
import { DataTools, DataStore, SessionService, TypeCheck, isNumber, isArrayOf } from '@kangaroo-and-rabbit/kar-cw';
import { Album, AlbumResource, UUID } from "app/back-api";
import { RESTConfig } from "app/back-api/rest-tools";
import { environment } from "environments/environment";
import { GenericDataService } from "./GenericDataService";
import {
DataTools,
DataStore,
SessionService,
TypeCheck,
isNumber,
isArrayOf,
} from "@kangaroo-and-rabbit/kar-cw";
@Injectable()
export class AlbumService extends GenericDataService<Album> {
getRestConfig(): RESTConfig {
return {
server: environment.server.karusic,
token: this.session.getToken(),
};
}
private lambdaGets(): Promise<Album[]> {
const self = this;
return AlbumResource.gets({ restConfig: this.getRestConfig() });
}
getRestConfig(): RESTConfig {
return {
server: environment.server.karusic,
token: this.session.getToken()
}
}
private lambdaGets(): Promise<Album[]> {
const self = this;
return AlbumResource.gets({ restConfig: this.getRestConfig() });
}
constructor(private session: SessionService) {
super();
console.log("Start AlbumService");
this.setStore(new DataStore<Album>(() => this.lambdaGets()));
}
constructor(private session: SessionService) {
super();
console.log('Start AlbumService');
this.setStore(new DataStore<Album>(() => this.lambdaGets()));
}
insert(data: Album): Promise<Album> {
const self = this;
return new Promise((resolve, reject) => {
AlbumResource.post({
restConfig: this.getRestConfig(),
data,
})
.then((value: Album) => {
self.dataStore.updateValue(value);
resolve(value);
})
.catch((error) => {
reject(error);
});
});
}
patch(id: number, data: Album): Promise<Album> {
const self = this;
return new Promise((resolve, reject) => {
AlbumResource.patch({
restConfig: this.getRestConfig(),
params: {
id,
},
data,
})
.then((value: Album) => {
self.dataStore.updateValue(value);
resolve(value);
})
.catch((error) => {
reject(error);
});
});
}
insert(data: Album): Promise<Album> {
const self = this;
return new Promise((resolve, reject) => {
AlbumResource.post({
restConfig: this.getRestConfig(),
data
}).then((value: Album) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
patch(id: number, data: Album): Promise<Album> {
const self = this;
return new Promise((resolve, reject) => {
AlbumResource.patch({
restConfig: this.getRestConfig(),
params: {
id
},
data
}).then((value: Album) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
delete(id: number): Promise<void> {
const self = this;
return new Promise((resolve, reject) => {
AlbumResource.remove({
restConfig: this.getRestConfig(),
params: {
id,
},
})
.then(() => {
self.dataStore.delete(id);
resolve();
})
.catch((error) => {
reject(error);
});
});
}
delete(id: number): Promise<void> {
const self = this;
return new Promise((resolve, reject) => {
AlbumResource.remove({
restConfig: this.getRestConfig(),
params: {
id
}
}).then(() => {
self.dataStore.delete(id);
resolve();
}).catch((error) => {
reject(error);
});
});
}
deleteCover(id: number, coverId: UUID): Promise<Album> {
let self = this;
return new Promise((resolve, reject) => {
AlbumResource.removeCover({
restConfig: this.getRestConfig(),
params: {
id,
coverId
}
}).then((value) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
uploadCover(id: number,
file: File,
progress: any = null): Promise<Album> {
let self = this;
return new Promise((resolve, reject) => {
AlbumResource.uploadCover({
restConfig: this.getRestConfig(),
params: {
id,
},
data: {
file,
}
}).then((value) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
/**
* Get all the artists for a specific album
* @param idAlbum - Id of the album.
* @returns a promise on the list of Artist ID for this album
*/
getArtists(idAlbum: number): Promise<number[]> {
let self = this;
return new Promise((resolve, reject) => {
self.gets()
.then((response: Album[]) => {
let data = DataTools.getsWhere(response,
[
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: idAlbum,
},
],
['name']);
// filter with artist- ID !!!
const listArtistId = DataTools.extractLimitOneList(data, "artists");
if (isArrayOf(listArtistId, isNumber)) {
resolve(listArtistId);
} else {
reject(`Fail to get the ids (impossible case) ${listArtistId}`);
}
}).catch((response) => {
reject(response);
});
});
}
deleteCover(id: number, coverId: UUID): Promise<Album> {
let self = this;
return new Promise((resolve, reject) => {
AlbumResource.removeCover({
restConfig: this.getRestConfig(),
params: {
id,
coverId,
},
})
.then((value) => {
self.dataStore.updateValue(value);
resolve(value);
})
.catch((error) => {
reject(error);
});
});
}
uploadCover(id: number, file: File, progress: any = null): Promise<Album> {
let self = this;
return new Promise((resolve, reject) => {
AlbumResource.uploadCover({
restConfig: this.getRestConfig(),
params: {
id,
},
data: {
file,
},
})
.then((value) => {
self.dataStore.updateValue(value);
resolve(value);
})
.catch((error) => {
reject(error);
});
});
}
/**
* Get all the artists for a specific album
* @param idAlbum - Id of the album.
* @returns a promise on the list of Artist ID for this album
*/
getArtists(idAlbum: number): Promise<number[]> {
let self = this;
return new Promise((resolve, reject) => {
self
.gets()
.then((response: Album[]) => {
let data = DataTools.getsWhere(
response,
[
{
check: TypeCheck.EQUAL,
key: "albumId",
value: idAlbum,
},
],
["name"]
);
// filter with artist- ID !!!
const listArtistId = DataTools.extractLimitOneList(data, "artists");
if (isArrayOf(listArtistId, isNumber)) {
resolve(listArtistId);
} else {
reject(`Fail to get the ids (impossible case) ${listArtistId}`);
}
})
.catch((response) => {
reject(response);
});
});
}
}

View File

@ -261,6 +261,7 @@ export const AudioPlayer = ({}: AudioPlayerProps) => {
max={duration}
step={0.1}
onChange={onSeek}
focusThumbOnChange={false}
>
<SliderTrack bg="gray.200" height="10px" borderRadius="full">
<SliderFilledTrack bg="brand.600" />

View File

@ -24,7 +24,7 @@ const helpList: HelpListType[] = [
},
];
export const HelpPage = async () => {
export const HelpPage = () => {
const { mode } = useThemeMode();
const navigate = useNavigate();
const onSelectItem = (data: HelpListType) => {
@ -35,7 +35,7 @@ export const HelpPage = async () => {
name: 'lkjlkj',
},
];
const result = await DataTools.getsWhere(
const result = DataTools.getsWhere(
testData,
[
{

View File

@ -37,12 +37,12 @@ export const useAlbumServiceWrapped = (
export const useOrderedAlbums = (titleFilter: string | undefined) => {
const { store } = useAlbumService();
const dataAlbums = useMemo(async () => {
const dataAlbums = useMemo(() => {
let tmpData = store.data;
if (!isNullOrUndefined(titleFilter)) {
tmpData = DataTools.getNameLike(tmpData, titleFilter);
}
return await DataTools.getsWhere(
return DataTools.getsWhere(
tmpData,
[
{

View File

@ -37,12 +37,12 @@ export const useArtistServiceWrapped = (
export const useOrderedArtists = (nameFilter: string | undefined) => {
const { store } = useArtistService();
const dataArtist = useMemo(async () => {
const dataArtist = useMemo(() => {
let tmpData = store.data;
if (!isNullOrUndefined(nameFilter)) {
tmpData = DataTools.getNameLike(tmpData, nameFilter);
}
return await DataTools.getsWhere(
return DataTools.getsWhere(
tmpData,
[
{

View File

@ -37,12 +37,12 @@ export const useGenderServiceWrapped = (
export const useOrderedGenders = (titleFilter: string | undefined) => {
const { store } = useGenderService();
const dataGenders = useMemo(async () => {
const dataGenders = useMemo(() => {
let tmpData = store.data;
if (!isNullOrUndefined(titleFilter)) {
tmpData = DataTools.getNameLike(tmpData, titleFilter);
}
return await DataTools.getsWhere(
return DataTools.getsWhere(
tmpData,
[
{

View File

@ -1,101 +0,0 @@
import { useDataStore } from '@/utils/data-store';
import { DataTools, TypeCheck } from '@/utils/data-tools';
import { isNullOrUndefined } from '@/utils/validator';
export class GenericDataService<TYPE> {
constructor(protected dataStore: DataStore<TYPE>) {}
gets(): Promise<TYPE[]> {
return this.dataStore.getData();
}
get(id: number): Promise<TYPE> {
let self = this;
return new Promise((resolve, reject) => {
self
.gets()
.then((response: TYPE[]) => {
let data = DataTools.get(response, id);
if (isNullOrUndefined(data)) {
reject('Data does not exist in the local BDD');
return;
}
resolve(data);
return;
})
.catch((response) => {
reject(response);
});
});
}
getAll(ids: number[]): Promise<TYPE[]> {
let self = this;
return new Promise((resolve, reject) => {
self
.gets()
.then(async (response: TYPE[]) => {
let data = await DataTools.getsWhere(response, [
{
check: TypeCheck.EQUAL,
key: 'id',
value: ids,
},
]);
resolve(data);
return;
})
.catch((response) => {
reject(response);
});
});
}
getLike(value: string): Promise<TYPE[]> {
let self = this;
return new Promise((resolve, reject) => {
self
.gets()
.then((response: TYPE[]) => {
let data = DataTools.getNameLike(response, value);
if (isNullOrUndefined(data) || data.length === 0) {
reject('Data does not exist in the local BDD');
return;
}
resolve(data);
return;
})
.catch((response) => {
reject(response);
});
});
}
getOrder(): Promise<TYPE[]> {
let self = this;
return new Promise((resolve, reject) => {
self
.gets()
.then(async (response: TYPE[]) => {
let data = await DataTools.getsWhere(
response,
[
{
check: TypeCheck.NOT_EQUAL,
key: 'id',
value: [undefined, null],
},
],
['name', 'id']
);
resolve(data);
})
.catch((response) => {
console.log(
`[E] ${self.constructor.name}: can not retrieve BDD values`
);
reject(response);
});
});
}
}

View File

@ -40,7 +40,7 @@ export const useSpecificTrack = (id: number | undefined) => {
const dataTrack = useMemo(() => {
return store.get(id);
}, [store.data, id]);
return { dataTrack };
return { isLoading: store.isLoading, dataTrack };
};
/**
* Get all the track for a specific artist
@ -49,28 +49,22 @@ export const useSpecificTrack = (id: number | undefined) => {
*/
export const useTracksOfAnArtist = (idArtist?: number) => {
const { store } = useTrackService();
const [tracksOnAnArtist, setTracksOnAnArtist] = useState<Track[]>([]);
useEffect(() => {
const tracksOnAnArtist = useMemo(() => {
if (idArtist) {
const tmpFunction = async () => {
const data = await DataTools.getsWhere(
store.data,
[
{
check: TypeCheck.CONTAINS,
key: 'artists',
value: idArtist,
},
],
['track', 'name']
);
setTracksOnAnArtist(data);
};
tmpFunction();
} else {
setTracksOnAnArtist([]);
return DataTools.getsWhere(
store.data,
[
{
check: TypeCheck.CONTAINS,
key: 'artists',
value: idArtist,
},
],
['track', 'name']
);
}
}, [store.data, idArtist, setTracksOnAnArtist]);
return [];
}, [store.data, idArtist]);
return { isLoading: store.isLoading, tracksOnAnArtist };
};
@ -80,12 +74,12 @@ export const useTracksOfAnArtist = (idArtist?: number) => {
* @returns The number of track present in this artist
*/
export const useCountTracksOfAnArtist = (idArtist: number) => {
const { tracksOnAnAlbum } = useTracksOfAnAlbum(idArtist);
const { isLoading, tracksOnAnAlbum } = useTracksOfAnAlbum(idArtist);
const countTracksOnAnArtist = useMemo(
() => tracksOnAnAlbum?.length ?? 0,
[tracksOnAnAlbum]
);
return { countTracksOnAnArtist };
return { isLoading, countTracksOnAnArtist };
};
/**
@ -95,29 +89,23 @@ export const useCountTracksOfAnArtist = (idArtist: number) => {
*/
export const useTracksOfAGender = (idGender?: number) => {
const { store } = useTrackService();
const [tracksOnAGender, setTracksOnAGender] = useState<Track[]>([]);
useEffect(() => {
const tracksOnAGender = useMemo(() => {
if (idGender) {
const tmpFunction = async () => {
const ret = await DataTools.getsWhere(
store.data,
[
{
check: TypeCheck.CONTAINS,
key: 'genderId',
value: idGender,
},
],
['name', 'track']
);
setTracksOnAGender(ret);
};
tmpFunction();
} else {
setTracksOnAGender([]);
return DataTools.getsWhere(
store.data,
[
{
check: TypeCheck.CONTAINS,
key: 'genderId',
value: idGender,
},
],
['name', 'track']
);
}
return [];
}, [store.data, idGender]);
return { tracksOnAGender };
return { isLoading: store.isLoading, tracksOnAGender };
};
/**
@ -126,12 +114,12 @@ export const useTracksOfAGender = (idGender?: number) => {
* @returns The number of track present in this artist
*/
export const useCountTracksOfAGender = (idGender?: number) => {
const { tracksOnAGender } = useTracksOfAGender(idGender);
const { isLoading, tracksOnAGender } = useTracksOfAGender(idGender);
const countTracksOnAGender = useMemo(
() => tracksOnAGender?.length ?? 0,
[tracksOnAGender]
);
return { countTracksOnAGender };
return { isLoading, countTracksOnAGender };
};
/**
@ -140,7 +128,7 @@ export const useCountTracksOfAGender = (idGender?: number) => {
* @returns the required List.
*/
export const useAlbumIdsOfAnArtist = (idArtist?: number) => {
const { tracksOnAnArtist } = useTracksOfAnArtist(idArtist);
const { isLoading, tracksOnAnArtist } = useTracksOfAnArtist(idArtist);
const albumIdsOfAnArtist = useMemo(() => {
// extract a single time all value "id" in an array
const listAlbumId = DataTools.extractLimitOne(tracksOnAnArtist, 'albumId');
@ -153,34 +141,27 @@ export const useAlbumIdsOfAnArtist = (idArtist?: number) => {
return [];
}
}, [tracksOnAnArtist]);
return { albumIdsOfAnArtist };
return { isLoading, albumIdsOfAnArtist };
};
export const useTracksOfAnAlbum = (idAlbum?: number) => {
const { store } = useTrackService();
const [tracksOnAnAlbum, setTracksOnAnAlbum] = useState<Track[]>();
useEffect(() => {
const tracksOnAnAlbum = useMemo(() => {
if (idAlbum) {
const tmpFunction = async () => {
const ret = await DataTools.getsWhere(
store.data,
[
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: idAlbum,
},
],
['track', 'name', 'id']
);
setTracksOnAnAlbum(ret);
};
tmpFunction();
} else {
setTracksOnAnAlbum([]);
return DataTools.getsWhere(
store.data,
[
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: idAlbum,
},
],
['track', 'name', 'id']
);
}
}, [store.data, idAlbum]);
return { tracksOnAnAlbum };
return { isLoading: store.isLoading, tracksOnAnAlbum };
};
/**
@ -189,12 +170,12 @@ export const useTracksOfAnAlbum = (idAlbum?: number) => {
* @returns The number of element present in this season
*/
export const useCountTracksWithAlbumId = (albumId?: number) => {
const { tracksOnAnAlbum } = useTracksOfAnAlbum(albumId);
const { isLoading, tracksOnAnAlbum } = useTracksOfAnAlbum(albumId);
const countTracksOfAnAlbum = useMemo(
() => tracksOnAnAlbum?.length ?? 0,
[tracksOnAnAlbum]
);
return { countTracksOfAnAlbum };
return { isLoading, countTracksOfAnAlbum };
};
/**
@ -204,35 +185,28 @@ export const useCountTracksWithAlbumId = (albumId?: number) => {
*/
export const useTracksOfArtistWithNoAlbum = (idArtist: number) => {
const { store } = useTrackService();
const [tracksOnAnArtistWithNoAlbum, setTracksOnAnArtistWithNoAlbum] =
useState<Track[]>([]);
useEffect(() => {
const tracksOnAnArtistWithNoAlbum = useMemo(() => {
if (idArtist) {
const tmpFunction = async () => {
const ret = await DataTools.getsWhere(
store.data,
[
{
check: TypeCheck.CONTAINS,
key: 'artists',
value: idArtist,
},
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: undefined,
},
],
['track', 'name']
);
setTracksOnAnArtistWithNoAlbum(ret);
};
tmpFunction();
} else {
setTracksOnAnArtistWithNoAlbum([]);
return DataTools.getsWhere(
store.data,
[
{
check: TypeCheck.CONTAINS,
key: 'artists',
value: idArtist,
},
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: undefined,
},
],
['track', 'name']
);
}
return [];
}, [store.data, idArtist]);
return { tracksOnAnArtistWithNoAlbum };
return { isLoading: store.isLoading, tracksOnAnArtistWithNoAlbum };
};
/**
@ -245,23 +219,18 @@ export const useTracksWithStartName = (
invert: boolean
) => {
const { store } = useTrackService();
const [tracksStartsWith, setTracksStartsWith] = useState<Track[]>([]);
useEffect(() => {
const tmpFunction = async () => {
const ret = await DataTools.getsWhere(
store.data,
[
{
check: invert ? TypeCheck.STARTS_NOT_WITH : TypeCheck.STARTS_WITH,
key: 'name',
value: startName,
},
],
['name', 'track']
);
setTracksStartsWith(ret);
};
tmpFunction();
const tracksStartsWith = useMemo(() => {
return DataTools.getsWhere(
store.data,
[
{
check: invert ? TypeCheck.STARTS_NOT_WITH : TypeCheck.STARTS_WITH,
key: 'name',
value: startName,
},
],
['name', 'track']
);
}, [store.data, startName, invert]);
return { isLoading: store.isLoading, tracksStartsWith };
};

View File

@ -6,7 +6,7 @@
import { DependencyList, useCallback, useEffect, useState } from 'react';
import { RestErrorResponse } from '@/back-api';
import { isNullOrUndefined } from '@/utils/validator';
import { isArray, isNullOrUndefined } from '@/utils/validator';
export type DataStoreType<TYPE> = {
isLoading: boolean;
@ -16,10 +16,6 @@ export type DataStoreType<TYPE> = {
gets: <MODEL>(value: MODEL[] | undefined, key?: string) => TYPE[];
};
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export const useDataStore = <TYPE>(
{
primaryKey = 'id',
@ -42,13 +38,10 @@ export const useDataStore = <TYPE>(
setError(undefined);
setIsLoading(true);
getsCall()
.then(async (response: TYPE[]) => {
.then((response: TYPE[]) => {
/*console.log(
`[${restApiName}] getData Response: ${JSON.stringify(response, null, 2)}`
);*/
console.log(`[${restApiName}] ${Date()} Receive data done (wait 10s)`);
await delay(10000);
console.log(`[${restApiName}] ${Date()} Ready`);
setData(response);
setError(undefined);
setIsLoading(false);

View File

@ -85,15 +85,13 @@ export namespace DataTools {
bdd: TYPE[],
select: SelectModel[],
orderByData?: string[]
): Promise<TYPE[]> {
return new Promise((resolve, _reject) => {
// console.log("[I] gets_where " + this.name + " select " + _select);
let tmpList = getSubList(bdd, select);
if (tmpList && orderByData) {
tmpList = orderBy(tmpList, orderByData);
}
resolve(tmpList);
});
): TYPE[] {
// console.log("[I] gets_where " + this.name + " select " + _select);
let tmpList = getSubList(bdd, select);
if (tmpList && orderByData) {
tmpList = orderBy(tmpList, orderByData);
}
return tmpList;
}
export function get<TYPE>(