Merge pull request #35 from gustavo-em/refactor_create_portal
Refactoring in the code of create new portal and bug fix when create demo serverpull/39/head
commit
1d0b5fefe4
@ -0,0 +1,46 @@
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import {ICreatePortal, IPortal, IPortalProp, IPortalToAdd} from './types';
|
||||
|
||||
export async function createNewPortal({
|
||||
name,
|
||||
url,
|
||||
}: ICreatePortal): Promise<IPortal[]> {
|
||||
let portalsStorage: IPortalProp = await getPortals();
|
||||
|
||||
if (portalsStorage === null || portalsStorage === '[]')
|
||||
return await createFromEmptyStorage(name, url);
|
||||
|
||||
portalsStorage = parseString(portalsStorage);
|
||||
|
||||
return await addPortalToStorage({portals: portalsStorage, name, url});
|
||||
}
|
||||
|
||||
async function createFromEmptyStorage(name: string, url: string) {
|
||||
await createStorageEmpty();
|
||||
let portalsStorage = await getPortals();
|
||||
const portalStorage = parseString(portalsStorage!);
|
||||
await addPortalToStorage({portals: portalStorage, name, url});
|
||||
return portalStorage;
|
||||
}
|
||||
|
||||
async function getPortals(): Promise<string | null> {
|
||||
return await AsyncStorage.getItem('portal');
|
||||
}
|
||||
|
||||
async function createStorageEmpty() {
|
||||
await AsyncStorage.setItem('portal', JSON.stringify([]));
|
||||
}
|
||||
|
||||
function parseString(portalsStorage: string): Array<IPortal> {
|
||||
return (portalsStorage = JSON.parse(portalsStorage));
|
||||
}
|
||||
|
||||
async function addPortalToStorage({
|
||||
portals,
|
||||
name,
|
||||
url,
|
||||
}: IPortalToAdd): Promise<IPortal[]> {
|
||||
portals.push({name, url});
|
||||
await AsyncStorage.setItem('portal', JSON.stringify(portals));
|
||||
return portals;
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import { usePortal } from "../../contexts/portals/hook";
|
||||
|
||||
export async function new_portal_name_and_url(name: string, url: string): Promise<object | Error> {
|
||||
try{
|
||||
let portalsStorage;
|
||||
portalsStorage = await AsyncStorage.getItem('portal');
|
||||
portalsStorage = portalsStorage ? JSON.parse(portalsStorage) : null;
|
||||
portalsStorage.push({name, url});
|
||||
AsyncStorage.setItem('portal', JSON.stringify(portalsStorage));
|
||||
return portalsStorage
|
||||
} catch(error){
|
||||
return Error("Error when try create a new portal")
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
export type ICreatePortal = {
|
||||
name: string;
|
||||
url: string;
|
||||
};
|
||||
|
||||
export type IPortal = {
|
||||
name: string;
|
||||
url: string;
|
||||
};
|
||||
|
||||
export type IPortalToAdd = {
|
||||
portals: Array<IPortal>;
|
||||
name: string;
|
||||
url: string;
|
||||
};
|
||||
|
||||
export type IPortalProp = string | null | IPortal[];
|
Loading…
Reference in new issue