-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFullstack_Part3_Exercise.txt
More file actions
627 lines (461 loc) · 12.7 KB
/
Fullstack_Part3_Exercise.txt
File metadata and controls
627 lines (461 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
3.1 - 3.6 Phonebook Backend
const express = require("express")
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
let persons = [
{
"name": "Arto Hellas",
"number": "040-123456",
"id": 1
},
{
"name": "Ada Lovelace",
"number": "39-44-5323523",
"id": 2
},
{
"name": "Dan Abramov",
"number": "12-43-234345",
"id": 3
},
{
"name": "Mary Poppendieck",
"number": "39-23-6423122",
"id": 4
}
]
app.get("/info", (req, res) => {
const date = new Date()
res.send(`<h1>Phonebook has info for ${persons.length} people</h1> <h2>${date}</h2>`)
})
app.get("/api/persons", (req, res) => {
res.json(persons)
})
app.get("/api/persons/:id", (req, res) => {
const id = Number(req.params.id)
const person = persons.find(person => person.id === id)
if (person) {
res.json(person)
} else {
res.status(404).end()
}
})
app.delete("/api/persons/:id", (req, res) => {
const id = Number(req.params.id)
persons = persons.filter(p => p.id !== id)
res.status(204).end()
})
const generateID = () => {
const Gid = Math.floor(Math.random() * 1000)
return Gid
}
app.post("/api/persons", (req, res) => {
const body = req.body
if (!body.name || !body.number) {
console.log("No content")
return res.status(400).json({
error: "Content Missing"
})
}
let a = persons.find(person => person.name === body.name)
if (a) {
return res.status(400).json({
error: "Name must be unique"
})
}
const personObject = {
name: body.name,
number: body.number,
id: generateID()
}
persons = persons.concat(personObject)
res.json(personObject)
})
const PORT = 3001
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})
3.7 - 3.8 Phonebook Backend
const express = require("express")
const app = express()
const bodyParser = require("body-parser")
const morgan = require("morgan")
app.use(bodyParser.json())
morgan.token("body", function(req, res) {
console.log(res)
return JSON.stringify(res.req.body)
})
app.use(morgan(':method :url :status :res[content-length] - :response-time ms :body'))
let persons = [
{
"name": "Arto Hellas",
"number": "040-123456",
"id": 1
},
{
"name": "Ada Lovelace",
"number": "39-44-5323523",
"id": 2
},
{
"name": "Dan Abramov",
"number": "12-43-234345",
"id": 3
},
{
"name": "Mary Poppendieck",
"number": "39-23-6423122",
"id": 4
}
]
app.get("/api/persons", (req, res) => {
res.json(persons)
})
const generateID = () => {
const Gid = Math.floor(Math.random() * 1000)
return Gid
}
app.post("/api/persons", (req, res) => {
const body = req.body
if (!body.name || !body.number) {
console.log("No content")
return res.status(400).json({
error: "Content Missing"
})
}
let a = persons.find(person => person.name === body.name)
if (a) {
return res.status(400).json({
error: "Name must be unique"
})
}
const personObject = {
name: body.name,
number: body.number,
id: generateID()
}
persons = persons.concat(personObject)
res.json(personObject)
})
const PORT = 3001
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})
3.9 - 3.11 Phonebook Backend -> Fullstack
***************************************************
Production Mode
FrontEnd:
https://aqueous-caverns-88259.herokuapp.com
BackEnd:
https://aqueous-caverns-88259.herokuapp.com/persons
Development Mode
FrontEnd:
http://localhost:3000
BackEnd:
http://localhost: 3001
3.12 Command-line database
const mongoose = require('mongoose')
if ( process.argv.length<5 ) {
console.log('give password as argument')
process.exit(1)
}
const password = process.argv[2]
const firstName = process.argv[3]
const lastName = process.argv[4]
const tele = process.argv[5]
const url =
`mongodb+srv://daisy:${password}@cluster0-vrqjx.mongodb.net/Database?retryWrites=true&w=majority`
mongoose.connect(url, { useNewUrlParser: true })
const noteSchema = new mongoose.Schema({
name: String,
telephone: String
})
const Note = mongoose.model('Note', noteSchema)
const note = new Note({
name: `${firstName} ${lastName}`,
telephone: String(tele)
})
note.save().then(response => {
console.log(`added ${firstName} number ${tele} to phonebook`)
mongoose.connection.close()
})
Note
.find({})
.then(response => {
console.log("Phonebook")
response.forEach(note => {
console.log(note.name, note.telephone)
})
mongoose.connection.close()
})
3.13 - 3.21 Phonebook Fullstack(Frontend +++ Backend +++ Database)
************************************************************Frontend: index.js************************************************************
import axios from "axios";
import React, {useState, useEffect} from "react";
import ReactDOM from "react-dom";
import Axios from "./Axios.js";
import cors from "cors"
const Notification = (props) => {
const style = {
color: "green",
fontSize: 30,
border: "2px solid green",
borderRadius: "10px",
margin: "20px",
paddingLeft: "20px"
}
if (props.message === null) {
return null
} else {
return (
<div style = {style}>
{props.message}
</div>
)
}
}
const App = () => {
const [ persons, setPersons ] = useState([])
const [ newName, setNewName ] = useState("")
const [ newNumber, setNewNumber ] = useState("")
const [ search, setSearch ] = useState("")
const [ showAll, setShowAll ] = useState(false)
const [ message, setMessage ] = useState("")
useEffect(() => {
Axios
.getAll()
.then(response => setPersons(response))
} , [])
const addPersons = (event) => {
const newObject = {
name: newName,
number: newNumber
}
Axios
.create(newObject)
.then(response => setPersons(persons.concat(response)))
setNewName("")
setNewNumber("")
setMessage(newName + " Added")
setTimeout(()=>setMessage(null), 2000)
}
const handleNameChange = (event) => {
setNewName(event.target.value)
}
const handleNumberChange = (event) => {
setNewNumber(event.target.value)
}
const handleSearch = (event) => {
setSearch(event.target.value)
setShowAll(true)
}
const Filter = (query) => {
const filter_result = persons.filter(person => person.name.toLowerCase().split(" ").join("").indexOf(query.toLowerCase()) !== -1)
return filter_result
}
const displayToShow = showAll
? Filter(search)
: persons
const handleDelete = (id) => {
Axios
.getOne(id)
.then(response => {
const result = window.confirm("Do you really want to delete " + response.name)
if (result) {
Axios
.deleteObject(id)
.then(response => console.log(response))
}
setTimeout(() => {
Axios
.getAll()
.then(response => setPersons(response))
}, 1000)
})
}
const handleChange = (name) => {
const person = persons.find(n => n.name === name)
const change = {...person, number:newNumber}
const id = person.id
const result = window.confirm(name + " is already added to Phonebook, replace the old number with a new one?")
if (result) {
Axios
.update(id, change)
.then(response => setPersons(persons.map(person => person.id === id ? response : person)))
}
}
return (
<div>
<h2>Phonebook</h2>
Search by Name: <input value = {search} onChange = {handleSearch} />
<Notification message = {message} />
<h2>Add A New Contact</h2>
<form onSubmit = {addPersons}>
Name: <input value = {newName} onChange = {handleNameChange} />
Number: <input value = {newNumber} onChange = {handleNumberChange} />
<br />
<br />
<button type = "submit">ADD</button>
</form>
<br />
<form onSubmit = {() => handleChange(newName)}>
<button type = "submit">Change Contact</button>
</form>
<h2>Numbers</h2>
{displayToShow.map(person => {
return(
<div key = {person.id}>
<p>{person.name}: {person.number}</p>
<button onClick = {() => handleDelete(person.id)}>Delete</button>
</div>
)})
}
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById('root'))
***********************************************************Frontend: Axios.js***************************************************************
import React from 'react';
import axios from "axios";
const baseUrl = "http://localhost:3001/persons"
const getAll = () => {
const request = axios.get(baseUrl)
return request.then(response => response.data)
}
const getOne = (id) => {
const request = axios.get(`${baseUrl}/${id}`)
return request.then(response => response.data)
}
const create = (newObject) => {
const request = axios.post(baseUrl, newObject)
return request.then(response => response.data)
}
const update = (id, newObject) => {
const request = axios.put(`${baseUrl}/${id}`, newObject)
return request.then(response => response.data)
}
const deleteObject = (id) => {
const request = axios.delete(`${baseUrl}/${id}`)
return request.then(response => response.data)
}
export default {getAll, getOne, create, update, deleteObject}
***********************************************************Backend: index.js***************************************************************
const express = require("express")
const app = express()
const bodyParser = require("body-parser")
const cors = require('cors')
const Person = require("./Mongoose")
app.use(cors())
app.use(express.static('build'))
app.use(bodyParser.json())
app.get("/persons", (req, res, next) => {
Person
.find({})
.then(people => {
res.json(people.map(person => person.toJSON()))
})
.catch(error => next(error))
})
app.get("/persons/:id" , (req, res) => {
const id = req.params.id
Person
.find({})
.then(people => {
const person = people.find(person => person.id === id)
if (person) {
res.json(person.toJSON())
} else {
res.status(404).end()
}
})
.catch(error => {
console.log(error)
res.status(400).send({error: "malformatted id"})
})
})
app.delete("/persons/:id", (req, res, next) => {
const id = req.params.id
Person
.findByIdAndRemove(id)
.then(result => {
res.status(204).end()
})
.catch(error => next(error))
})
app.post("/persons" , (req, res, next) => {
const body = req.body
if (!body.name || !body.number) {
return res.status(400).json({error: "information missing"})
}
const person = new Person({
name: body.name,
number: body.number
})
person
.save()
.then(Savedperson => {
res.json(Savedperson.toJSON)
})
.catch(error => next(error))
})
app.put('/persons/:id', (req, res, next) => {
const body = req.body
const id = req.params.id
const person = {
name: body.name,
number: body.number
}
Person
.findByIdAndUpdate(id, person, { new: true })
.then(updatedNote => {
res.json(updatedNote.toJSON())
})
.catch(error => next(error))
})
const errorHandler = (error, req, res, next) => {
console.log(error)
res.status(404).end()
}
app.use(errorHandler)
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})
***********************************************************Backend: Mongoose.js***************************************************************
const mongoose = require('mongoose')
const validator = require("mongoose-unique-validator")
const url = process.env.MONGODB_URI
console.log('connecting to', url)
mongoose.connect(url, { useFindAndModify: false, useCreateIndex: true, useUnifiedTopology: true, useNewUrlParser: true })
.then(result => {
console.log('connected to MongoDB')
})
.catch((error) => {
console.log('error connecting to MongoDB:', error.message)
})
const personSchema = new mongoose.Schema({
name: {
type: String,
minlength: 5,
unique: true,
required: true
},
number: {
type: String,
minlength: 10,
required: true
}
})
personSchema.plugin(validator)
personSchema.set('toJSON', {
transform: (document, person) => {
person.id = person._id.toString()
delete person._id
delete person.__v
}
})
module.exports = mongoose.model('Person', personSchema)