You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
1.9 KiB
75 lines
1.9 KiB
import express from 'express' |
|
import bodyParser from 'body-parser' |
|
import cors from 'cors' |
|
import mongoose from 'mongoose' |
|
|
|
import Todo from './todo.model' |
|
|
|
const app = express() |
|
const PORT = 4000 |
|
|
|
app.use(cors()) |
|
app.use(bodyParser.json()) |
|
|
|
app.listen(PORT, function () { |
|
console.log(`Server is running on Port: ${PORT}`) |
|
}) |
|
|
|
mongoose.connect('mongodb://localhost:27017/todos?authSource=admin', { |
|
useNewUrlParser: true, |
|
useUnifiedTopology: true, |
|
user: "admin", |
|
pass: "admin" |
|
}) |
|
|
|
const connection = mongoose.connection |
|
|
|
connection.on('error', console.error.bind(console, 'connection error:')) |
|
connection.once('open', function () { |
|
console.log('Connected successfully to mongodb server') |
|
}) |
|
|
|
const todoRoutes = express.Router() |
|
|
|
app.use('/todos', todoRoutes) |
|
|
|
todoRoutes.route('/').get((req, res) => { |
|
Todo.find((err, todos) => { |
|
if (err) { |
|
console.log(err) |
|
} else { |
|
res.json(todos) |
|
} |
|
}) |
|
}) |
|
|
|
todoRoutes.route('/:id').get((req, res) => { |
|
let id = req.params.id |
|
Todo.findById(id, (err, todo) => { |
|
res.json(todo) |
|
}) |
|
}) |
|
|
|
todoRoutes.route('/add').post((req, res) => { |
|
let todo = new Todo(req.body) |
|
todo.save() |
|
.then(todo => { res.status(200).json({ 'todo': 'todo added successfully' }) }) |
|
.catch(err => { res.status(400).send('adding new todo failed') }) |
|
}) |
|
|
|
todoRoutes.route('/update/:id').post((req, res) => { |
|
Todo.findById(req.params.id, (err, todo) => { |
|
if (!todo) { |
|
res.status(404).send("data is not found") |
|
} else { |
|
todo.todo_description = req.body.todo_description |
|
todo.todo_responsible = req.body.todo_responsible |
|
todo.todo_priority = req.body.todo_priority |
|
todo.todo_completed = req.body.todo_completed |
|
|
|
todo.save() |
|
.then(todo => res.json('Todo updated!')) |
|
.catch(err => res.status(400).send("Error while updating")) |
|
} |
|
}) |
|
})
|
|
|