├── README.md
├── client
├── public
│ ├── robots.txt
│ ├── favicon.ico
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── index.html
├── src
│ ├── setupTests.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── App.js
│ ├── App.css
│ ├── logo.svg
│ └── serviceWorker.js
└── package.json
├── config
├── default.json
└── db.js
├── notes.txt
├── models
├── User.js
└── Contact.js
├── middleware
└── auth.js
├── server.js
├── package.json
├── routes
├── users.js
├── contacts.js
└── auth.js
└── .gitignore
/README.md:
--------------------------------------------------------------------------------
1 | # contact-keeper
2 | MERN - Mongodb, Express, React, & Node js
3 |
--------------------------------------------------------------------------------
/client/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/client/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xchanmolx/contact-keeper/HEAD/client/public/favicon.ico
--------------------------------------------------------------------------------
/client/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xchanmolx/contact-keeper/HEAD/client/public/logo192.png
--------------------------------------------------------------------------------
/client/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xchanmolx/contact-keeper/HEAD/client/public/logo512.png
--------------------------------------------------------------------------------
/config/default.json:
--------------------------------------------------------------------------------
1 | {
2 | "mongoURI": "mongodb+srv://chan123:chan123@contactkeeper-637jj.mongodb.net/test?retryWrites=true&w=majority",
3 | "jwtSecret": "secret"
4 | }
--------------------------------------------------------------------------------
/client/src/setupTests.js:
--------------------------------------------------------------------------------
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/extend-expect';
6 |
--------------------------------------------------------------------------------
/client/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import App from './App';
4 |
5 | test('renders learn react link', () => {
6 | const { getByText } = render();
7 | const linkElement = getByText(/learn react/i);
8 | expect(linkElement).toBeInTheDocument();
9 | });
10 |
--------------------------------------------------------------------------------
/client/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 |
--------------------------------------------------------------------------------
/notes.txt:
--------------------------------------------------------------------------------
1 | React Front To Back 2019
2 |
3 | Lesson 44. Add Contact Route
4 | Video: 4:39
5 |
6 | Create database username on Mongodb and Cluster name
7 | git clone
8 | npm init -y
9 | "main": "index.js" to "server.js"
10 | npm i express bcryptjs jsonwebtoken config express-validator mongoose
11 | npm i -D nodemon concurrently
12 | create scripts -> "start": "node server.js",
13 | create scripts -> "server": "nodemon server.js"
14 | run a server: npm run server
15 | step 1: create routes
16 |
--------------------------------------------------------------------------------
/models/User.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 |
3 | const UserSchema = mongoose.Schema({
4 | name: {
5 | type: String,
6 | required: true
7 | },
8 | email: {
9 | type: String,
10 | required: true,
11 | unique: true
12 | },
13 | password: {
14 | type: String,
15 | required: true
16 | },
17 | date: {
18 | type: Date,
19 | default: Date.now
20 | },
21 | });
22 |
23 | module.exports = mongoose.model('user', UserSchema);
--------------------------------------------------------------------------------
/client/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 |
7 | ReactDOM.render(
8 |
9 |
10 | ,
11 | document.getElementById('root')
12 | );
13 |
14 | // If you want your app to work offline and load faster, you can change
15 | // unregister() to register() below. Note this comes with some pitfalls.
16 | // Learn more about service workers: https://bit.ly/CRA-PWA
17 | serviceWorker.unregister();
18 |
--------------------------------------------------------------------------------
/config/db.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 | const config = require('config');
3 | const db = config.get('mongoURI');
4 |
5 | const connectDB = async () => {
6 | try {
7 | await mongoose.connect(db, {
8 | useNewUrlParser: true,
9 | useCreateIndex: true,
10 | useFindAndModify: false,
11 | useUnifiedTopology: true
12 | });
13 |
14 | console.log('MongoDB Connected...');
15 | } catch (err) {
16 | console.error(err.message);
17 | process.exit(1);
18 | }
19 | };
20 |
21 | module.exports = connectDB;
--------------------------------------------------------------------------------
/client/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 |
--------------------------------------------------------------------------------
/middleware/auth.js:
--------------------------------------------------------------------------------
1 | const jwt = require('jsonwebtoken');
2 | const config = require('config');
3 |
4 | module.exports = function(req, res, next) {
5 | // Get token from header
6 | const token = req.header('x-auth-token');
7 |
8 | // Check if not token
9 | if(!token) {
10 | return res.status(401).json({ msg: 'No token, authorization denied' });
11 | }
12 |
13 | try {
14 | const decoded = jwt.verify(token, config.get('jwtSecret'));
15 |
16 | req.user = decoded.user;
17 | next();
18 | } catch (err) {
19 | res.status(401).json({ msg: 'Token is not valid' });
20 | }
21 | }
--------------------------------------------------------------------------------
/server.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const connectDB = require('./config/db');
3 |
4 | const app = express();
5 |
6 | // Connect Database
7 | connectDB();
8 |
9 | // Init Middleware
10 | app.use(express.json({ extended: false }));
11 |
12 | app.get('/', (req, res) => res.json({ msg: 'Welcome to the ContactKeeper API...'}));
13 |
14 | // Define Routes
15 | app.use('/api/users', require('./routes/users'));
16 | app.use('/api/auth', require('./routes/auth'));
17 | app.use('/api/contacts', require('./routes/contacts'));
18 |
19 | const PORT = process.env.PORT || 5000;
20 |
21 | app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
--------------------------------------------------------------------------------
/models/Contact.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 |
3 | const ContactSchema = mongoose.Schema({
4 | user: {
5 | type: mongoose.Schema.Types.ObjectId,
6 | ref: 'users'
7 | },
8 | name: {
9 | type: String,
10 | required: true
11 | },
12 | email: {
13 | type: String,
14 | required: true
15 | },
16 | phone: {
17 | type: String
18 | },
19 | type: {
20 | type: String,
21 | default: 'personal'
22 | },
23 | date: {
24 | type: Date,
25 | default: Date.now
26 | },
27 | });
28 |
29 | module.exports = mongoose.model('contact', ContactSchema);
--------------------------------------------------------------------------------
/client/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import logo from './logo.svg';
3 | import './App.css';
4 |
5 | function App() {
6 | return (
7 |
23 | );
24 | }
25 |
26 | export default App;
27 |
--------------------------------------------------------------------------------
/client/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 |
--------------------------------------------------------------------------------
/client/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "client",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^4.2.4",
7 | "@testing-library/react": "^9.5.0",
8 | "@testing-library/user-event": "^7.2.1",
9 | "react": "^16.13.1",
10 | "react-dom": "^16.13.1",
11 | "react-scripts": "3.4.1"
12 | },
13 | "scripts": {
14 | "start": "react-scripts start",
15 | "build": "react-scripts build",
16 | "test": "react-scripts test",
17 | "eject": "react-scripts eject"
18 | },
19 | "eslintConfig": {
20 | "extends": "react-app"
21 | },
22 | "browserslist": {
23 | "production": [
24 | ">0.2%",
25 | "not dead",
26 | "not op_mini all"
27 | ],
28 | "development": [
29 | "last 1 chrome version",
30 | "last 1 firefox version",
31 | "last 1 safari version"
32 | ]
33 | },
34 | "proxy": "http://localhost:5000"
35 | }
36 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "contact-keeper",
3 | "version": "1.0.0",
4 | "description": "Contact Manager App -> MERN - Mongodb, Express, React, & Node js",
5 | "main": "server.js",
6 | "scripts": {
7 | "start": "node server.js",
8 | "server": "nodemon server.js",
9 | "client": "npm start --prefix client",
10 | "clientinstall": "npm install --prefix client",
11 | "dev": "concurrently \"npm run server\" \"npm run client\""
12 | },
13 | "repository": {
14 | "type": "git",
15 | "url": "git+https://github.com/xchanmolx/contact-keeper.git"
16 | },
17 | "keywords": [],
18 | "author": "",
19 | "license": "ISC",
20 | "bugs": {
21 | "url": "https://github.com/xchanmolx/contact-keeper/issues"
22 | },
23 | "homepage": "https://github.com/xchanmolx/contact-keeper#readme",
24 | "dependencies": {
25 | "bcryptjs": "^2.4.3",
26 | "config": "^3.3.0",
27 | "express": "^4.17.1",
28 | "express-validator": "^6.4.0",
29 | "jsonwebtoken": "^8.5.1",
30 | "mongoose": "^5.9.4"
31 | },
32 | "devDependencies": {
33 | "concurrently": "^5.1.0",
34 | "nodemon": "^2.0.2"
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/client/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 |
--------------------------------------------------------------------------------
/routes/users.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const bcrypt = require('bcryptjs');
4 | const jwt = require('jsonwebtoken');
5 | const config = require('config');
6 | const { check, validationResult } = require('express-validator');
7 |
8 | const User = require('../models/User');
9 |
10 | // @route POST api/users
11 | // @desc Register a user
12 | // @access Public
13 | router.post('/', [
14 | check('name', 'Please add name').not().isEmpty(),
15 | check('email', 'Please include a valid email').isEmail(),
16 | check('password', 'Please enter a password with 6 or more characters').isLength({
17 | min: 6
18 | })
19 | ], async (req, res) => {
20 | const errors = validationResult(req);
21 | if(!errors.isEmpty()) {
22 | return res.status(400).json({ errors: errors.array() });
23 | }
24 |
25 | const { name, email, password } = req.body;
26 |
27 | try {
28 | let user = await User.findOne({ email });
29 |
30 | if(user) {
31 | return res.status(400).json({ msg: 'User already exists' })
32 | }
33 |
34 | user = new User({
35 | name,
36 | email,
37 | password
38 | });
39 |
40 | const salt = await bcrypt.genSalt(10);
41 |
42 | user.password = await bcrypt.hash(password, salt);
43 |
44 | await user.save();
45 |
46 | const payload = {
47 | user: {
48 | id: user.id
49 | }
50 | }
51 |
52 | jwt.sign(payload, config.get('jwtSecret'), {
53 | expiresIn: 360000
54 | }, (err, token) => {
55 | if(err) throw err;
56 | res.json({ token });
57 | });
58 |
59 | } catch (err) {
60 | console.error(err.message);
61 | res.status(500).send('Server Error');
62 | }
63 | });
64 |
65 | module.exports = router;
--------------------------------------------------------------------------------
/routes/contacts.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const auth = require('../middleware/auth');
4 | const { check, validationResult } = require('express-validator');
5 |
6 | const User = require('../models/User');
7 | const Contact = require('../models/Contact');
8 |
9 | // @route GET api/contacts
10 | // @desc Get all users contacts
11 | // @access Private
12 | router.get('/', auth, async (req, res) => {
13 | try {
14 | const contacts = await Contact.find({ user: req.user.id }).sort({ date: -1 });
15 | res.json(contacts);
16 | } catch (err) {
17 | console.error(err.message);
18 | res.status(500).send('Server Error');
19 | }
20 | });
21 |
22 | // @route POST api/contacts
23 | // @desc Add new contact
24 | // @access Private
25 | router.post('/', [ auth, [
26 | check('name', 'Name is required').not().isEmpty()
27 | ] ], async (req, res) => {
28 | const errors = validationResult(req);
29 | if(!errors.isEmpty()) {
30 | return res.status(400).json({ errors: errors.array() });
31 | }
32 |
33 | const { name, email, phone, type } = req.body;
34 |
35 | try {
36 | const newContact = new Contact({
37 | name,
38 | email,
39 | phone,
40 | type,
41 | user: req.user.id
42 | });
43 |
44 | const contact = await newContact.save();
45 |
46 | res.json(contact);
47 | } catch (err) {
48 | console.error(err.message);
49 | res.status(500).send('Server Error');
50 | }
51 | });
52 |
53 | // @route PUT api/contacts/:id
54 | // @desc Update contact
55 | // @access Private
56 | router.put('/:id', (req, res) => {
57 | res.send('Update contact');
58 | });
59 |
60 | // @route DELETE api/contacts/:id
61 | // @desc Delete contact
62 | // @access Private
63 | router.delete('/:id', (req, res) => {
64 | res.send('Delete contact');
65 | });
66 |
67 | module.exports = router;
--------------------------------------------------------------------------------
/routes/auth.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const bcrypt = require('bcryptjs');
4 | const jwt = require('jsonwebtoken');
5 | const config = require('config');
6 | const auth = require('../middleware/auth');
7 | const { check, validationResult } = require('express-validator');
8 |
9 | const User = require('../models/User');
10 |
11 | // @route GET api/auth
12 | // @desc Get logged in user
13 | // @access Private
14 | router.get('/', auth, async (req, res) => {
15 | try {
16 | const user = await User.findById(req.user.id).select('-password');
17 | res.json(user);
18 | } catch (err) {
19 | console.error(err.message);
20 | res.status(500).send('Server Error');
21 | }
22 | });
23 |
24 | // @route POST api/auth
25 | // @desc Auth user & get token
26 | // @access Public
27 | router.post('/', [
28 | check('email', 'Please include a valid email').isEmail(),
29 | check('password', 'Password is required').exists()
30 | ], async (req, res) => {
31 | const errors = validationResult(req);
32 | if(!errors.isEmpty()) {
33 | return res.status(400).json({ errors: errors.array() });
34 | }
35 |
36 | const { email, password } = req.body;
37 |
38 | try {
39 | let user = await User.findOne({ email });
40 |
41 | if(!user) {
42 | return res.status(400).json({ msg: 'Invalid Credentials' });
43 | }
44 |
45 | const isMatch = await bcrypt.compare(password, user.password);
46 |
47 | if(!isMatch) {
48 | return res.status(400).json({ msg: 'Invalid Credentials' });
49 | }
50 |
51 | const payload = {
52 | user: {
53 | id: user.id
54 | }
55 | }
56 |
57 | jwt.sign(payload, config.get('jwtSecret'), {
58 | expiresIn: 360000
59 | }, (err, token) => {
60 | if(err) throw err;
61 | res.json({ token });
62 | });
63 |
64 | } catch (err) {
65 | console.error(err.message);
66 | res.status(500).send('Server Error');
67 | }
68 | });
69 |
70 | module.exports = router;
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | node_modules/
3 | logs
4 | *.log
5 | npm-debug.log*
6 | yarn-debug.log*
7 | yarn-error.log*
8 | lerna-debug.log*
9 |
10 | # Diagnostic reports (https://nodejs.org/api/report.html)
11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
12 |
13 | # Runtime data
14 | pids
15 | *.pid
16 | *.seed
17 | *.pid.lock
18 |
19 | # Directory for instrumented libs generated by jscoverage/JSCover
20 | lib-cov
21 |
22 | # Coverage directory used by tools like istanbul
23 | coverage
24 | *.lcov
25 |
26 | # nyc test coverage
27 | .nyc_output
28 |
29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
30 | .grunt
31 |
32 | # Bower dependency directory (https://bower.io/)
33 | bower_components
34 |
35 | # node-waf configuration
36 | .lock-wscript
37 |
38 | # Compiled binary addons (https://nodejs.org/api/addons.html)
39 | build/Release
40 |
41 | # Dependency directories
42 | node_modules/
43 | jspm_packages/
44 |
45 | # TypeScript v1 declaration files
46 | typings/
47 |
48 | # TypeScript cache
49 | *.tsbuildinfo
50 |
51 | # Optional npm cache directory
52 | .npm
53 |
54 | # Optional eslint cache
55 | .eslintcache
56 |
57 | # Microbundle cache
58 | .rpt2_cache/
59 | .rts2_cache_cjs/
60 | .rts2_cache_es/
61 | .rts2_cache_umd/
62 |
63 | # Optional REPL history
64 | .node_repl_history
65 |
66 | # Output of 'npm pack'
67 | *.tgz
68 |
69 | # Yarn Integrity file
70 | .yarn-integrity
71 |
72 | # dotenv environment variables file
73 | .env
74 | .env.test
75 |
76 | # parcel-bundler cache (https://parceljs.org/)
77 | .cache
78 |
79 | # Next.js build output
80 | .next
81 |
82 | # Nuxt.js build / generate output
83 | .nuxt
84 | dist
85 |
86 | # Gatsby files
87 | .cache/
88 | # Comment in the public line in if your project uses Gatsby and *not* Next.js
89 | # https://nextjs.org/blog/next-9-1#public-directory-support
90 | # public
91 |
92 | # vuepress build output
93 | .vuepress/dist
94 |
95 | # Serverless directories
96 | .serverless/
97 |
98 | # FuseBox cache
99 | .fusebox/
100 |
101 | # DynamoDB Local files
102 | .dynamodb/
103 |
104 | # TernJS port file
105 | .tern-port
106 |
--------------------------------------------------------------------------------
/client/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/client/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' },
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister();
136 | })
137 | .catch(error => {
138 | console.error(error.message);
139 | });
140 | }
141 | }
142 |
--------------------------------------------------------------------------------