Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature - API Implementation #35

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17,863 changes: 17,550 additions & 313 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
"@types/node": "^16.11.22",
"@types/react": "^17.0.38",
"@types/react-dom": "^17.0.11",
"axios": "^1.4.0",
"moment": "^2.29.4",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",
Expand Down Expand Up @@ -43,7 +45,8 @@
},
"devDependencies": {
"cross-env": "^7.0.3",
"msw": "^0.36.8"
"msw": "^0.36.8",
"tailwindcss": "^3.3.2"
},
"msw": {
"workerDirectory": "public"
Expand Down
23 changes: 3 additions & 20 deletions src/App.css
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
.App {
text-align: center;
}

.App-logo {
height: 40vmin;
pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
Expand All @@ -18,21 +9,13 @@
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
align-items: left;
justify-content: flex-start;
font-size: calc(10px + 2vmin);
color: white;
padding: 20px;
}

.App-link {
color: #61dafb;
}

@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
33 changes: 16 additions & 17 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
import React from 'react';
import logo from './logo.svg';
import './App.css';
/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect } from "react";
import "./App.css";
import useAuthViewModel from "./Presentation/Auth/AuthViewModel";
import { AppointmentsView } from "./Presentation/Appointments/AppointmentsView";

function App() {
const { data: AuthToken, getAuthToken } = useAuthViewModel();

useEffect(() => {
getAuthToken();
}, []);

const renderClinicsView = AuthToken?.authToken ? (
<AppointmentsView />
) : undefined;

return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
<header className="App-header">{renderClinicsView}</header>
</div>
);
}
Expand Down
42 changes: 42 additions & 0 deletions src/Core/Axios/HttpClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import axios, {
AxiosInstance,
AxiosRequestHeaders,
AxiosResponse,
} from "axios";
import { BASE_URL } from "../constants";

export abstract class HttpClient {
protected instance: AxiosInstance | undefined;

protected createInstance(): AxiosInstance {
this.instance = axios.create({
baseURL: BASE_URL,
headers: {
"Content-Type": "application/json",
},
});
this.initializeResponseInterceptor();
return this.instance;
}

private initializeResponseInterceptor = () => {
this.instance!.interceptors.response.use(
this.handleResponse,
this.handleError
);
const token = sessionStorage.getItem("authToken");
this.instance!.interceptors.request.use((config) => {
if (!config.url?.includes("login")) {
config.headers = {
Authorization: `Bearer ${token}`,
} as AxiosRequestHeaders;
}

return config;
});
};

private handleResponse = ({ data }: AxiosResponse) => data;

private handleError = (error: any) => Promise.reject(error);
}
77 changes: 77 additions & 0 deletions src/Core/BaseRepository/BaseRepository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { AxiosResponse } from "axios";
import { HttpClient } from "../Axios/HttpClient";

export interface IBaseRepository<T, S = void> {
get(id: any): Promise<T>;
customGet(): Promise<T>;
getMany(): Promise<T[]>;
create(item: T): Promise<T>;
update(id: any, item: T): Promise<T>;
delete(id: any): Promise<T>;
getAuthToken(credentials: S): Promise<T>;
}

const transform = (response: AxiosResponse): Promise<any> => {
return new Promise((resolve, reject) => {
resolve(response);
});
};

export abstract class BaseRepository<T, S = void>
extends HttpClient
implements IBaseRepository<T, S>
{
protected collection!: string;

public async get(path: string): Promise<T> {
const instance = this.createInstance();
const result = await instance
.get(`/${this.collection}/${path}`)
.then(transform);
return result as T;
}

public async customGet(): Promise<T> {
const instance = this.createInstance();
const result = await instance.get(`/${this.collection}`).then(transform);
return result as T;
}

public async getMany(): Promise<T[]> {
const instance = this.createInstance();
const result = await instance.get(`/${this.collection}/`).then(transform);
return result as T[];
}

public async create(item: T): Promise<T> {
const instance = this.createInstance();
const result = await instance
.post(`/${this.collection}/`, item)
.then(transform);
return result as T;
}

public async update(id: string, item: T): Promise<T> {
const instance = this.createInstance();
const result = await instance
.put(`/${this.collection}/${id}`, item)
.then(transform);
return result as T;
}

public async delete(id: any): Promise<T> {
const instance = this.createInstance();
const result = await instance
.delete(`/${this.collection}/${id}`)
.then(transform);
return result as T;
}

public async getAuthToken(credentials: S): Promise<T> {
const instance = this.createInstance();
const result = await instance
.post(`/${this.collection}`, credentials)
.then(transform);
return result as T;
}
}
9 changes: 9 additions & 0 deletions src/Core/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export const BASE_URL = "/api";

export const ENDPOINT_LOGIN = "/login";

export const ENDPOINT_APPOINTMENTS = "/appointments";

export const ENDPOINT_CLINICS = "/clinics";

export const ENDPOINT_CLINIC = (id: string): string => `/clinic/${id}`;
File renamed without changes.
File renamed without changes.
104 changes: 104 additions & 0 deletions src/Core/mocks/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { rest } from "msw";
import {
ApiError,
AppointmentsDto,
Clinic,
ClinicsDto,
Login,
LoginResponse,
} from "../zoomcare-api";
import { mockClinics } from "./data/clinics";
import { mockAppointmentSlots } from "./data/appointmentSlots";

const mockAuthToken = Math.random().toString(36).slice(2);

export const handlers = [
rest.get<any, any, AppointmentsDto | ApiError>(
"/api/appointments",
(req, res, context) => {
if (!req.headers.get("Authorization")?.includes(mockAuthToken)) {
return res(
context.status(403),
context.json({
error: "Not Authorized",
})
);
}

return res(
context.status(200),
context.json({
appointmentSlots: mockAppointmentSlots,
})
);
}
),

rest.get<any, any, ClinicsDto | ApiError>(
"/api/clinics",
(req, res, context) => {
if (!req.headers.get("Authorization")?.includes(mockAuthToken)) {
return res(
context.status(403),
context.json({
error: "Not Authorized",
})
);
}

return res(
context.status(200),
context.json({
clinics: mockClinics,
})
);
}
),

rest.get<any, { clinicId: string }, Clinic | ApiError>(
"/api/clinics/:clinicId",
(req, res, context) => {
if (!req.headers.get("Authorization")?.includes(mockAuthToken)) {
return res(
context.status(403),
context.json({
error: "Not Authorized",
})
);
}

const { clinicId } = req.params;

const clinic = mockClinics.find((c) => c.id === parseInt(clinicId, 10));
if (clinic) {
return res(context.status(200), context.json(clinic));
} else {
return res(
context.status(404),
context.json({
error: `No clinic found with id='${clinicId}'`,
})
);
}
}
),

// consumes and produces "application/json" only
rest.post<Login, any, LoginResponse>("/api/login", (req, res, ctx) => {
const { username, password } = req.body;
if (!!username && !!password) {
sessionStorage.setItem("username", username);
sessionStorage.setItem("authToken", mockAuthToken);
return res(
// Respond with a 200 status code
ctx.status(200),
ctx.json({
username: username,
authToken: mockAuthToken,
})
);
} else {
return res(ctx.status(400));
}
}),
];
File renamed without changes.
File renamed without changes.
File renamed without changes.
7 changes: 7 additions & 0 deletions src/Core/utils/fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
interface TypedResponse<T = any> extends Response {
json<P = T>(): Promise<P>;
}

export function myFetch<T>(...args: any): Promise<TypedResponse<T>> {
return fetch.apply(window, args);
}
9 changes: 9 additions & 0 deletions src/Core/utils/formatPhoneNumber.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function formatPhoneNumber(phoneNumberString: string) {
var cleaned = ("" + phoneNumberString).replace(/\D/g, "");
var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/);
if (match) {
var intlCode = match[1] ? "+1 " : "";
return [intlCode, "(", match[2], ") ", match[3], "-", match[4]].join("");
}
return null;
}
Loading