Add Services folder and use service to interact with API

This commit is contained in:
Ruidy Nemausat 2020-04-20 15:55:19 +02:00
parent 024d2a58f3
commit 9d4769101a
15 changed files with 306 additions and 136 deletions

BIN
app.db

Binary file not shown.

View file

@ -16,9 +16,8 @@ export class UserVM {
public projects: Project[];
public tickets: Ticket[];
public activities: Activity[];
public allUsers: User[];
public constructor(user: User, allUsers: User[]) {
public constructor(user: User) {
this.id = user.id;
this.firstName = user.firstName;
this.lastName = user.lastName;
@ -31,6 +30,5 @@ export class UserVM {
this.projects = user.projects;
this.tickets = user.tickets;
this.activities = user.activities;
this.allUsers = allUsers;
}
}

View file

@ -27,10 +27,9 @@ const useStyles = makeStyles((theme: Theme) =>
type IProps = {
projects: Project[];
allUsers: User[];
};
const ProjectList: FC<IProps> = ({ projects, allUsers }) => {
const ProjectList: FC<IProps> = ({ projects }) => {
const [filterText, setFilterText] = useState<string>("");
const clearFilterText: (e: MouseEvent) => void = (e: MouseEvent) => {
setFilterText("");
@ -59,7 +58,6 @@ const ProjectList: FC<IProps> = ({ projects, allUsers }) => {
setShowNew(false);
}}
show={showNew}
allUsers={allUsers}
/>
<Grid container>
<Grid

View file

@ -5,17 +5,19 @@ import Project from "../../types/Project";
import User from "../../types/User";
import { post } from "../../utils/http";
import Constants from "../../utils/Constants";
import { useAuth0 } from "../../authentication/auth0";
import { ProjectService } from "../../services";
interface IProps {
show: boolean;
handleClose: () => void;
allUsers: User[];
}
const NewProjectModal: FC<IProps> = ({ show, handleClose }) => {
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [endingDate, setEndingDate] = useState("");
const { getTokenSilently, user } = useAuth0();
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
@ -26,7 +28,9 @@ const NewProjectModal: FC<IProps> = ({ show, handleClose }) => {
managerId: "cd179eb7-3a54-4060-b22c-3e947bdffcbc", // get current User id
};
await post<Project>(`${Constants.projectsURI}`, newProject);
const token = await getTokenSilently();
const Projects = new ProjectService(token);
await Projects.add(newProject);
handleClose();
};

View file

@ -13,8 +13,8 @@ import Project from "../../types/Project";
import Category from "../../types/enums/category";
import Impact from "../../types/enums/impact";
import Difficulty from "../../types/enums/difficulty";
import { post } from "../../utils/http";
import Constants from "../../utils/Constants";
import { TicketService } from "../../services";
import { useAuth0 } from "../../authentication/auth0";
interface IProps {
show: boolean;
@ -39,6 +39,7 @@ const NewTicketModal: FC<IProps> = ({ show, handleClose, allProjects }) => {
const [categoryID, setCategoryID] = useState(0);
const [impactID, setImpactID] = useState(0);
const [difficultyID, setDifficultyID] = useState(0);
const { getTokenSilently, user } = useAuth0();
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
@ -53,8 +54,9 @@ const NewTicketModal: FC<IProps> = ({ show, handleClose, allProjects }) => {
category: categoryID,
};
// const response: HttpResponse<Ticket> =
await post<Ticket>(`${Constants.ticketsURI}`, newTicket);
const token = await getTokenSilently();
const Tickets = new TicketService(token);
await Tickets.add(newTicket);
handleClose();
};

View file

@ -51,15 +51,9 @@ interface IProps {
tabNames: string[];
tickets: Ticket[];
projects: Project[];
allUsers: User[];
}
const UserTabPanel: FC<IProps> = ({
tickets,
tabNames,
projects,
allUsers,
}) => {
const UserTabPanel: FC<IProps> = ({ tickets, tabNames, projects }) => {
const classes = useStyles();
const theme = useTheme();
const [value, setValue] = useState(0);
@ -94,7 +88,7 @@ const UserTabPanel: FC<IProps> = ({
onChangeIndex={handleChangeIndex}
>
<TabPanel value={value} index={0} dir={theme.direction}>
<ProjectList projects={projects} allUsers={allUsers} />
<ProjectList projects={projects} />
</TabPanel>
<TabPanel value={value} index={1} dir={theme.direction}>
<TicketList tickets={tickets} allProjects={[]} addButton={false} />

View file

@ -3,12 +3,11 @@ import { useParams } from "react-router-dom";
import ErrorController from "./ErrorController";
import ProjectPage from "../pages/ProjectPage";
import ProjectVM from "../VM/ProjectVM";
import HttpResponse from "../types/HttpResponse";
import Project from "../types/Project";
import User from "../types/User";
import Preloader from "../components/Preloader";
import Constants from "../utils/Constants";
import { get } from "../utils/http";
import { ProjectService, UserService } from "../services";
import { useAuth0 } from "../authentication/auth0";
const ProjectController: FC = () => {
const [project, setProject] = useState<Project>({} as Project);
@ -18,56 +17,57 @@ const ProjectController: FC = () => {
const [hasError, setHasError] = useState(false);
const [error, setError] = useState("");
const { id } = useParams();
async function httpGetProjects(id: string): Promise<void> {
try {
const response: HttpResponse<Project> = await get<Project>(
`${Constants.projectsURI}/${id}`
);
if (response.parsedBody !== undefined) {
setProject(response.parsedBody);
setIsLoading(false);
}
} catch (ex) {
console.error(ex);
setHasError(true);
setError(ex);
}
}
async function httpGetAllUsers(): Promise<void> {
try {
const response: HttpResponse<User> = await get<User>(
`${Constants.usersURI}`
);
if (response.parsedBody !== undefined) {
setAllUsers((response.parsedBody as unknown) as User[]);
}
} catch (ex) {
setHasError(true);
setError(ex);
}
}
async function httpGetAllProjects(): Promise<void> {
try {
const response: HttpResponse<Project> = await get<Project>(
`${Constants.projectsURI}`
);
if (response.parsedBody !== undefined) {
setAllProjects((response.parsedBody as unknown) as Project[]);
}
} catch (ex) {
setHasError(true);
setError(ex);
}
}
const { getTokenSilently } = useAuth0();
useEffect(() => {
const getProject = async (id: string): Promise<void> => {
const token = await getTokenSilently();
try {
const Projects = new ProjectService(token);
const project: Project = await Projects.get(id);
if (project !== undefined) {
setProject(project);
setIsLoading(false);
}
} catch (ex) {
setHasError(true);
setError(ex);
}
};
const getAllUsers = async (): Promise<void> => {
const token = await getTokenSilently();
try {
const Users = new UserService(token);
const response: User[] = await Users.all();
if (response !== undefined) {
setAllUsers(response);
setIsLoading(false);
}
} catch (ex) {
setHasError(true);
setError(ex);
}
};
const getAllProjects = async (): Promise<void> => {
const token = await getTokenSilently();
try {
const Projects = new ProjectService(token);
const response: Project[] = await Projects.all();
if (response !== undefined) {
setAllProjects(response);
}
} catch (ex) {
setHasError(true);
setError(ex);
}
};
if (id !== undefined) {
httpGetProjects(id);
httpGetAllUsers();
httpGetAllProjects();
getProject(id);
getAllUsers();
getAllProjects();
} else {
setHasError(true);
setError("Bad Request");

View file

@ -3,11 +3,10 @@ import { useParams } from "react-router-dom";
import ErrorController from "./ErrorController";
import TicketPage from "../pages/TicketPage";
import TicketVM from "../VM/TicketVM";
import HttpResponse from "../types/HttpResponse";
import Ticket from "../types/Ticket";
import Preloader from "../components/Preloader";
import { get } from "../utils/http";
import Constants from "../utils/Constants";
import { useAuth0 } from "../authentication/auth0";
import { TicketService } from "../services";
const TicketController: FC = () => {
const [isLoading, setIsLoading] = useState(true);
@ -15,26 +14,26 @@ const TicketController: FC = () => {
const [hasError, setHasError] = useState(false);
const [error, setError] = useState("");
const { id } = useParams();
async function httpGetTicket(id: string): Promise<void> {
try {
const response: HttpResponse<Ticket> = await get<Ticket>(
`${Constants.ticketsURI}/${id}`
);
if (response.parsedBody !== undefined) {
setTicket(response.parsedBody);
setIsLoading(false);
}
} catch (ex) {
console.error(ex);
setHasError(true);
setError(ex);
}
}
const { getTokenSilently } = useAuth0();
useEffect(() => {
const getTicket = async (id: string): Promise<void> => {
const token = await getTokenSilently();
try {
const Tickets = new TicketService(token);
const response: Ticket = await Tickets.get(id);
if (response !== undefined) {
setTicket(response);
setIsLoading(false);
}
} catch (ex) {
setHasError(true);
setError(ex);
}
};
if (id !== undefined) {
httpGetTicket(id);
getTicket(id);
} else {
setHasError(true);
setError("Bad Request");

View file

@ -3,54 +3,39 @@ import { useParams } from "react-router-dom";
import ErrorController from "./ErrorController";
import UserPage from "../pages/UserPage";
import { UserVM } from "../VM/UserVM";
import HttpResponse from "../types/HttpResponse";
import User from "../types/User";
import Preloader from "../components/Preloader";
import Constants from "../utils/Constants";
import { get } from "../utils/http";
import { UserService } from "../services";
import { useAuth0 } from "../authentication/auth0";
const UserController: FC = () => {
const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState<User>({} as User);
const [hasError, setHasError] = useState(false);
const [error, setError] = useState("");
const [allUsers, setAllUsers] = useState<User[]>([]);
const { id } = useParams();
async function httpGetUser(id: string): Promise<void> {
try {
const response: HttpResponse<User> = await get<User>(
`${Constants.usersURI}/${id}`
);
if (response.parsedBody !== undefined) {
setUser(response.parsedBody);
setIsLoading(false);
}
} catch (ex) {
console.error(ex);
setHasError(true);
setError(ex);
}
}
async function httpGetAllUsers(): Promise<void> {
try {
const response: HttpResponse<User> = await get<User>(
`${Constants.usersURI}`
);
if (response.parsedBody !== undefined) {
setAllUsers((response.parsedBody as unknown) as User[]);
}
} catch (ex) {
setHasError(true);
setError(ex);
}
}
const { getTokenSilently } = useAuth0();
useEffect(() => {
const getUser = async (id: string): Promise<void> => {
try {
const token = await getTokenSilently();
const Users = new UserService(token);
const response: User = await Users.get(id);
if (response !== undefined) {
setUser(response);
setIsLoading(false);
}
} catch (ex) {
console.error(ex);
setHasError(true);
setError(ex);
}
};
if (id !== undefined) {
httpGetUser(id);
httpGetAllUsers();
getUser(id);
} else {
setHasError(true);
setError("Bad Request");
@ -61,7 +46,7 @@ const UserController: FC = () => {
return <ErrorController error={error} />;
}
const viewModel = new UserVM(user, allUsers);
const viewModel = new UserVM(user);
return isLoading ? <Preloader /> : <UserPage viewModel={viewModel} />;
};

View file

@ -9,14 +9,7 @@ interface IProps {
}
const UserPage: FC<IProps> = ({ viewModel }) => {
const {
fullName,
presentation,
picture,
projects,
tickets,
allUsers,
} = viewModel;
const { fullName, presentation, picture, projects, tickets } = viewModel;
const tabNames: string[] = ["Projects", "Tickets"];
return (
@ -33,7 +26,6 @@ const UserPage: FC<IProps> = ({ viewModel }) => {
tabNames={tabNames}
projects={projects}
tickets={tickets}
allUsers={allUsers}
/>
}
/>

View file

@ -0,0 +1,72 @@
import HttpResponse from "../types/HttpResponse";
export default class HttpHandler<T> {
private newHeaders = async (token: string) => {
// const { getTokenSilently } = useAuth0();
// const token = await getTokenSilently();
return new Headers({
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
});
};
private execute = async (request: RequestInfo): Promise<HttpResponse<T>> => {
const response: HttpResponse<T> = await fetch(request);
try {
response.parsedBody = await response.json();
} catch (ex) {}
if (!response.ok) {
throw response.statusText;
}
return response;
};
get = async (path: string, token: string): Promise<HttpResponse<T>> => {
const args: RequestInit = {
method: "get",
headers: await this.newHeaders(token),
};
return await this.execute(new Request(path, args));
};
post = async (
path: string,
body: any,
token: string
): Promise<HttpResponse<T>> => {
const args: RequestInit = {
method: "post",
headers: await this.newHeaders(token),
body: JSON.stringify(body),
};
return await this.execute(new Request(path, args));
};
put = async (
path: string,
body: any,
token: string
): Promise<HttpResponse<T>> => {
const args: RequestInit = {
method: "put",
headers: await this.newHeaders(token),
body: JSON.stringify(body),
};
return await this.execute(new Request(path, args));
};
patch = async (
path: string,
body: any,
token: string
): Promise<HttpResponse<T>> => {
const args: RequestInit = {
method: "patch",
headers: await this.newHeaders(token),
body: JSON.stringify(body),
};
return await this.execute(new Request(path, args));
};
}

View file

@ -0,0 +1,13 @@
import ProjectService from "./project";
import TicketService from "./ticket";
import UserService from "./user";
export default interface IService<T> {
all(): Promise<T[]>;
get(id: string): Promise<T>;
add(item: any): Promise<void>;
update(id: string, item: T): Promise<void>;
delete(id: string): Promise<void>;
}
export { ProjectService, TicketService, UserService };

View file

@ -0,0 +1,38 @@
import IService from ".";
import Project from "../types/Project";
import HttpHandler from "./http";
interface NewProject {
title: string;
description: string;
endingDate: string;
managerId: string;
}
export default class ProjectService implements IService<Project> {
constructor(private key: string) {}
private http = new HttpHandler<Project>();
private path: string = "/api/v1/projects";
all = async (): Promise<Project[]> => {
const response = await this.http.get(this.path, this.key);
return (response.parsedBody as unknown) as Project[];
};
get = async (id: string): Promise<Project> => {
const response = await this.http.get(`${this.path}/${id}`, this.key);
const body = response.parsedBody;
return body ?? ({} as Project);
};
add = async (item: NewProject): Promise<void> => {
await this.http.post(this.path, item, this.key);
};
update(id: string, item: Project): Promise<void> {
throw new Error("Method not implemented.");
}
delete(id: string): Promise<void> {
throw new Error("Method not implemented.");
}
}

View file

@ -0,0 +1,42 @@
import IService from ".";
import Ticket from "../types/Ticket";
import HttpHandler from "./http";
interface NewTicket {
title: string;
description: string;
endingDate: string;
creatorId: string;
projectId: number;
impact: number;
difficulty: number;
category: number;
}
export default class TicketService implements IService<Ticket> {
constructor(private key: string) {}
private http = new HttpHandler<Ticket>();
private path: string = "/api/v1/tickets";
all = async (): Promise<Ticket[]> => {
const response = await this.http.get(this.path, this.key);
return (response.parsedBody as unknown) as Ticket[];
};
get = async (id: string): Promise<Ticket> => {
const response = await this.http.get(`${this.path}/${id}`, this.key);
const body = response.parsedBody;
return body ?? ({} as Ticket);
};
add = async (item: NewTicket): Promise<void> => {
await this.http.post(this.path, item, this.key);
};
update(id: string, item: Ticket): Promise<void> {
throw new Error("Method not implemented.");
}
delete(id: string): Promise<void> {
throw new Error("Method not implemented.");
}
}

View file

@ -0,0 +1,33 @@
import IService from ".";
import User from "../types/User";
import HttpHandler from "./http";
export default class UserService implements IService<User> {
constructor(private key: string) {}
private http = new HttpHandler<User>();
private path: string = "/api/v1/users";
all = async (): Promise<User[]> => {
const response = await this.http.get(this.path, this.key);
return (response.parsedBody as unknown) as User[];
};
get = async (id: string): Promise<User> => {
const response = await this.http.get(`${this.path}/${id}`, this.key);
const body = response.parsedBody;
return body ?? ({} as User);
};
add = async (item: User): Promise<void> => {
await this.http.post(this.path, item, this.key);
};
update = async (id: string, item: User): Promise<void> => {
throw new Error("Method not implemented.");
};
delete = async (id: string): Promise<void> => {
throw new Error("Method not implemented.");
};
}