Skip to content

Commit

Permalink
ex 3.20
Browse files Browse the repository at this point in the history
  • Loading branch information
alex-fedorenk0 committed Oct 3, 2022
1 parent b4779a3 commit 9d35e36
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 11 deletions.
27 changes: 18 additions & 9 deletions part3/phonebook-backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,26 @@ app.post('/api/persons', (request, response, next) => {
// error: "name or number missing"
// })
// }

const newPerson = new Person ({
name: body.name,
number: body.number,
Person.countDocuments({ name: body.name })
.then(count => {
if (count > 0) {
return response.status(400).json({
error: 'name already exists'
})
} else {
const newPerson = new Person ({
name: body.name,
number: body.number,
})

newPerson.save()
.then(savedPerson => {
response.json(savedPerson)
})
.catch(error => next(error))
}
})

newPerson.save()
.then(savedPerson => {
response.json(savedPerson)
})
.catch(error => next(error))
})

// unknown endpoint middleware
Expand Down
4 changes: 4 additions & 0 deletions part3/phonebook-backend/models/person.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ const personSchema = new mongoose.Schema({
},
number: {
type: String,
minLength: 8,
validate: num => {
return /\d{2,3}-\d{5,}/.test(num)
},
required: true
}
})
Expand Down
4 changes: 2 additions & 2 deletions part3/phonebook-backend/requests/new_person.rest
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ POST http://localhost:3001/api/persons/
Content-Type: application/json

{
"name": "John Show",
"number": "1111-111-112"
"name": "test3",
"number": "111-111112"
}

0 comments on commit 9d35e36

Please sign in to comment.