|
@@ -0,0 +1,47 @@
|
|
|
+const mongoose = require('mongoose')
|
|
|
+const express = require('express')
|
|
|
+const app = express()
|
|
|
+const port = 3000
|
|
|
+const bodyParser = require('body-parser')
|
|
|
+
|
|
|
+mongoose.connect('mongodb://localhost/chat', {useNewUrlParser: true});
|
|
|
+
|
|
|
+let db = mongoose.connection;
|
|
|
+
|
|
|
+let messageSchema = new mongoose.Schema({
|
|
|
+ nick: String,
|
|
|
+ message: String
|
|
|
+});
|
|
|
+
|
|
|
+let Message = mongoose.model('Message', messageSchema);
|
|
|
+
|
|
|
+db.on('error', console.error.bind(console, 'connection error:'));
|
|
|
+
|
|
|
+app.use(bodyParser.json())
|
|
|
+
|
|
|
+app.get('/message', async (req, res) => res.send(await Message.find()))
|
|
|
+app.get('/message/:id', async (req, res) =>
|
|
|
+ res.send(
|
|
|
+ await Message.findOne({_id: mongoose.Types.ObjectId(req.params.id)})
|
|
|
+ )
|
|
|
+)
|
|
|
+
|
|
|
+app.post('/message', async (req, res) => {
|
|
|
+ let newMessage = new Message(req.body)
|
|
|
+ await newMessage.save()
|
|
|
+ res.status(201).send(newMessage)
|
|
|
+})
|
|
|
+
|
|
|
+
|
|
|
+app.patch('/message/:id', async (req, res) => {
|
|
|
+ let msg = await Message.findOne({_id: mongoose.Types.ObjectId(req.params.id)})
|
|
|
+ let patch = req.body
|
|
|
+ Object.assign(msg, patch) // копирует и прото
|
|
|
+ await msg.save()
|
|
|
+ res.status(200).send(msg)
|
|
|
+
|
|
|
+})
|
|
|
+
|
|
|
+
|
|
|
+app.listen(port, () => console.log(`Example app listening on port ${port}!`))
|
|
|
+
|