Skip to content
Snippets Groups Projects
Commit 63ac1cfc authored by Suvi Hyvönen's avatar Suvi Hyvönen
Browse files

osa3

parents
No related branches found
No related tags found
No related merge requests found
node_modules
web: node index.js
index.js 0 → 100644
//toimivat 3.1-3.6
const http = require('http')
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
const cors = require('cors')
app.use(cors())
let persons = [
{
name: "Arto Hellas",
number: "040-123456",
id: 1
},
{
name: "Martti Tienari",
number: "040-123456",
id: 2
},
{
name: "Arto Järvinen",
number: "040-123456",
id: 3
},
{
name: "Lea Kutvonen",
number: "040-123456",
id: 4
}
]
app.get('/', (req, res) => {
res.send('<h1>Hello World!</h1>')
})
app.get('/api/persons', (req, res) => {
res.json(persons)
})
app.get('/api/persons/:id', (request, response) => {
const id = Number(request.params.id)
const person = persons.find(person => person.id === id )
if (person){
response.json(person)
}else{
response.status(404).end()
}
})
app.delete('/api/persons/:id' , (request, response) =>{
const id = Number(request.params.id)
persons = persons.filter(person => person.id !== id)
response.status(204).end()
})
const generateId = () => {
const minId = Math.ceil(persons.length > 0 ? persons.map(n => n.id).sort((a,b) => a - b).reverse()[0] : 1)
const maxId = Math.floor(1000)
return Math.floor(Math.random() * (maxId - minId));
}
app.post('/api/persons', (request, response) => {
const body = request.body
const person_list = () => persons.map(part => part.name)
if ((body.name && body.number) === undefined) {
return response.status(400).json({error: 'Please check the input, there is some content missing.'})
}
if ((person_list().includes(body.name))){
return response.status(400).json({error: 'Sorry, but the name must be unique.'})
console.log("name must be unique!");
}
const person = {
name: body.name,
number: body.number,
id: generateId()
}
persons = persons.concat(person)
response.json(person)
})
const error = (request, response) => {
response.status(404).send({error: 'unknown endpoint'})
}
app.use(error)
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})
{
"name": "osa3",
"version": "1.0.0",
"description": "osa3",
"main": "index.js",
"scripts": {
"start": "node index.js",
"watch": "nodemon index.js"
},
"author": "Suvi Hyvonen",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.16.4"
},
"devDependencies": {
"nodemon": "^1.18.10"
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment