├── .env ├── .gitignore ├── README.md ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── src ├── App.css ├── App.test.tsx ├── App.tsx ├── api │ ├── authApi.ts │ └── catsApi.ts ├── index.css ├── index.tsx ├── logo.svg ├── model │ └── cat.ts ├── react-app-env.d.ts ├── reportWebVitals.ts ├── services │ └── HttpApiService.ts └── setupTests.ts ├── tsconfig.json └── yarn.lock /.env: -------------------------------------------------------------------------------- 1 | REACT_APP_API_URI=http://localhost:5000 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `yarn start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 13 | 14 | The page will reload if you make edits.\ 15 | You will also see any lint errors in the console. 16 | 17 | ### `yarn test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `yarn build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `yarn eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 35 | 36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 39 | 40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-typescript-axios-starter", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.11.4", 7 | "@testing-library/react": "^11.1.0", 8 | "@testing-library/user-event": "^12.1.10", 9 | "@types/jest": "^26.0.15", 10 | "@types/node": "^12.0.0", 11 | "@types/react": "^17.0.0", 12 | "@types/react-dom": "^17.0.0", 13 | "@types/styled-components": "^5.1.15", 14 | "axios": "^0.24.0", 15 | "js-cookie": "^3.0.1", 16 | "jwt-decode": "^3.1.2", 17 | "react": "^17.0.2", 18 | "react-dom": "^17.0.2", 19 | "react-scripts": "4.0.3", 20 | "styled-components": "^5.3.3", 21 | "typescript": "^4.1.2", 22 | "web-vitals": "^1.0.1" 23 | }, 24 | "scripts": { 25 | "start": "react-scripts start", 26 | "build": "react-scripts build", 27 | "test": "react-scripts test", 28 | "eject": "react-scripts eject" 29 | }, 30 | "eslintConfig": { 31 | "extends": [ 32 | "react-app", 33 | "react-app/jest" 34 | ] 35 | }, 36 | "browserslist": { 37 | "production": [ 38 | ">0.2%", 39 | "not dead", 40 | "not op_mini all" 41 | ], 42 | "development": [ 43 | "last 1 chrome version", 44 | "last 1 firefox version", 45 | "last 1 safari version" 46 | ] 47 | }, 48 | "devDependencies": { 49 | "@types/js-cookie": "^3.0.0" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Surprise080504/react-typescript-axios-starter/ff37a6a6df5205151a40745db24d67853f2d3525/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Surprise080504/react-typescript-axios-starter/ff37a6a6df5205151a40745db24d67853f2d3525/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Surprise080504/react-typescript-axios-starter/ff37a6a6df5205151a40745db24d67853f2d3525/public/logo512.png -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/App.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render, screen } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | test('renders learn react link', () => { 6 | render(); 7 | const linkElement = screen.getByText(/learn react/i); 8 | expect(linkElement).toBeInTheDocument(); 9 | }); 10 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import logo from './logo.svg'; 3 | import './App.css'; 4 | import styled from 'styled-components'; 5 | import { findAllCats, createCat } from '../src/api/catsApi'; 6 | import { Cat } from './model/cat'; 7 | 8 | const Button = styled.button` 9 | background: purple; 10 | border-radius: 3px; 11 | border: none; 12 | color: white; 13 | padding: 10px; 14 | radius: 5px; 15 | cursor: pointer; 16 | `; 17 | 18 | const Container = styled.div` 19 | display: flex; 20 | flex-direction: row; 21 | width: 30%; 22 | justify-content: space-between; 23 | `; 24 | 25 | function App() { 26 | 27 | const findAll = async () => { 28 | const response = await findAllCats(); 29 | } 30 | 31 | const create = async () => { 32 | const newCat: Cat = { 33 | name: "Kitty", 34 | age: 3, 35 | breed: "Baby Kitty" 36 | } 37 | const response = await createCat(newCat); 38 | } 39 | 40 | return ( 41 |
42 |
43 | logo 44 |

45 | Cats Api with NestJS 46 |

47 | 48 | 49 | 50 | 51 |
52 |
53 | ); 54 | } 55 | 56 | export default App; 57 | -------------------------------------------------------------------------------- /src/api/authApi.ts: -------------------------------------------------------------------------------- 1 | import Cookies from 'js-cookie'; 2 | import jwtDecode from 'jwt-decode'; 3 | 4 | const ACCESS_TOKEN = 'access_token'; 5 | 6 | const isTokenValid = (token: string) => { 7 | try { 8 | const decoded: { exp: number } = jwtDecode(token) 9 | return new Date(decoded.exp * 1000) > new Date() 10 | } catch { 11 | return false 12 | } 13 | } 14 | 15 | const login = (token: string) => { 16 | Cookies.set(ACCESS_TOKEN, token) 17 | } 18 | 19 | const logout = () => { 20 | Cookies.remove(ACCESS_TOKEN) 21 | } 22 | 23 | const getToken = () => Cookies.get(ACCESS_TOKEN) 24 | 25 | const isAuthenticated = () => { 26 | const token = getToken() 27 | 28 | if (!token) { 29 | return false 30 | } 31 | return true // isTokenValid(token) 32 | } 33 | 34 | export default { 35 | login, 36 | logout, 37 | getToken, 38 | isAuthenticated, 39 | isTokenValid, 40 | } 41 | 42 | -------------------------------------------------------------------------------- /src/api/catsApi.ts: -------------------------------------------------------------------------------- 1 | import HttpApiService from '../services/HttpApiService'; 2 | import { Cat } from '../model/cat'; 3 | 4 | const API_BASE = `${process.env.REACT_APP_API_URI}`; 5 | const CATS_ENDPOINT = `${API_BASE}/cats`; 6 | 7 | const httpApiService: HttpApiService = new HttpApiService(API_BASE); 8 | 9 | export const findAllCats = () => { 10 | return httpApiService.get(`${CATS_ENDPOINT}`); 11 | } 12 | 13 | export const createCat = (createCat: Cat) => { 14 | return httpApiService.post(`${CATS_ENDPOINT}`, createCat); 15 | } -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | 7 | ReactDOM.render( 8 | 9 | 10 | , 11 | document.getElementById('root') 12 | ); 13 | 14 | // If you want to start measuring performance in your app, pass a function 15 | // to log results (for example: reportWebVitals(console.log)) 16 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 17 | reportWebVitals(); 18 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/model/cat.ts: -------------------------------------------------------------------------------- 1 | export interface Cat { 2 | name: string; 3 | age: number; 4 | breed: string; 5 | } -------------------------------------------------------------------------------- /src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /src/reportWebVitals.ts: -------------------------------------------------------------------------------- 1 | import { ReportHandler } from 'web-vitals'; 2 | 3 | const reportWebVitals = (onPerfEntry?: ReportHandler) => { 4 | if (onPerfEntry && onPerfEntry instanceof Function) { 5 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 6 | getCLS(onPerfEntry); 7 | getFID(onPerfEntry); 8 | getFCP(onPerfEntry); 9 | getLCP(onPerfEntry); 10 | getTTFB(onPerfEntry); 11 | }); 12 | } 13 | }; 14 | 15 | export default reportWebVitals; 16 | -------------------------------------------------------------------------------- /src/services/HttpApiService.ts: -------------------------------------------------------------------------------- 1 | import axios, { AxiosInstance, AxiosPromise, AxiosResponse } from 'axios'; 2 | 3 | class HttpApiService { 4 | private _axiosInstance: AxiosInstance | undefined; 5 | private _baseURL: string; 6 | private _token: string | null; 7 | 8 | constructor(baseURL: string) { 9 | this._baseURL = baseURL; 10 | this._token = null; 11 | 12 | this.createAxiosInstance(); 13 | } 14 | 15 | private defaultOptions = (): any => { 16 | // Set the AUTH token for any request 17 | 18 | const authHttpHeader = "Bearer token" // Token goes here 19 | this._token = authHttpHeader; 20 | 21 | const options = { 22 | baseURL: this._baseURL, 23 | // withCredentials: true, // Window Authentification 24 | headers: { 25 | 'Accept': 'application/json', 26 | // 'Authorization': `${authHttpHeader}` // OAuth Authetification 27 | } 28 | }; 29 | return options; 30 | }; 31 | 32 | /** 33 | * Create instance 34 | */ 35 | private createAxiosInstance() { 36 | this._axiosInstance = axios.create(this.defaultOptions()); 37 | // this.checkAutorization() 38 | 39 | // Add a request interceptor 40 | this._axiosInstance.interceptors.request.use( 41 | config => config, 42 | error => { 43 | return Promise.reject(error); 44 | } 45 | ); 46 | 47 | // Add a response interceptor 48 | this._axiosInstance.interceptors.response.use( 49 | this.handleSuccess, 50 | this.handleError 51 | ); 52 | } 53 | 54 | public getToken() { 55 | return this._token; 56 | } 57 | 58 | public get(endpoint: string, conf = {}): AxiosPromise { 59 | return new Promise((resolve, reject) => { 60 | this._axiosInstance! 61 | .get(`${endpoint}`, conf) 62 | .then(response => { 63 | resolve(response); 64 | }) 65 | .catch(error => { 66 | reject(error); 67 | }); 68 | }); 69 | } 70 | 71 | public create(endpoint: string, data: {}, conf = {}): AxiosPromise { 72 | return this.post(endpoint, data, conf) 73 | } 74 | 75 | public post(endpoint: string, data: {}, conf = {}): AxiosPromise { 76 | return new Promise((resolve, reject) => { 77 | this._axiosInstance! 78 | .post(`${endpoint}`, data, conf) 79 | .then(response => { 80 | resolve(response); 81 | }) 82 | .catch(error => { 83 | reject(error); 84 | }); 85 | }); 86 | } 87 | 88 | public update(endpoint: string, data: {}, conf = {}): AxiosPromise { 89 | return new Promise((resolve, reject) => { 90 | this._axiosInstance! 91 | .put(`${endpoint}`, data, conf) 92 | .then(response => { 93 | resolve(response); 94 | }) 95 | .catch(error => { 96 | reject(error); 97 | }); 98 | }); 99 | } 100 | 101 | public delete(endpoint: string, id: any, conf = {}): AxiosPromise { 102 | return new Promise((resolve, reject) => { 103 | this._axiosInstance! 104 | .delete(`${endpoint}/${id}`, conf) 105 | .then(response => { 106 | resolve(response); 107 | }) 108 | .catch(error => { 109 | reject(error); 110 | }); 111 | }); 112 | } 113 | 114 | public deleteFile(endpoint: string, conf = {}): AxiosPromise { 115 | return new Promise((resolve, reject) => { 116 | this._axiosInstance! 117 | .delete(`${endpoint}`, conf) 118 | .then(response => { 119 | resolve(response); 120 | }) 121 | .catch(error => { 122 | reject(error); 123 | }); 124 | }); 125 | } 126 | 127 | public uploadFile(endpoint: string, data: FormData, conf = {}): AxiosPromise { 128 | return this.post(endpoint, data, conf) 129 | } 130 | 131 | public downloadFile(endpoint: string): AxiosPromise { 132 | const conf = { 133 | responseType: 'blob', // important 134 | timeout: 30000, 135 | } 136 | return this.get(endpoint, conf) 137 | } 138 | 139 | handleSuccess(response: AxiosResponse) { 140 | // console.log('handleSuccess' + JSON.stringify(response)) 141 | return response; 142 | } 143 | 144 | handleError = (err: any) => { 145 | console.log(`HttpService::Error : ${err}`) 146 | if (!err.response) { 147 | console.log(`Network error: ${err}`); 148 | } else { 149 | if (err.response !== undefined) { 150 | const { status } = err.response; 151 | if (status === 401 || status === 500) { 152 | console.log(`HttpService::Error(401 or 500) : ${err.response.data.Message}`) 153 | } 154 | } 155 | } 156 | return Promise.reject(err); 157 | }; 158 | 159 | redirectTo = (document: any, path: string) => { 160 | document.location = path; 161 | }; 162 | } 163 | 164 | export default HttpApiService; -------------------------------------------------------------------------------- /src/setupTests.ts: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "noFallthroughCasesInSwitch": true, 16 | "module": "esnext", 17 | "moduleResolution": "node", 18 | "resolveJsonModule": true, 19 | "isolatedModules": true, 20 | "noEmit": true, 21 | "jsx": "react-jsx" 22 | }, 23 | "include": [ 24 | "src" 25 | ] 26 | } 27 | --------------------------------------------------------------------------------