Skip to content

Commit

Permalink
Added socket.io
Browse files Browse the repository at this point in the history
  • Loading branch information
rosemdev committed Feb 28, 2024
1 parent 3762312 commit 6edfb2c
Show file tree
Hide file tree
Showing 5 changed files with 454 additions and 5 deletions.
11 changes: 10 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,15 @@ app.use((error, req, res, next) => {
mongoose
.connect(process.env.FEED_DB_CONNECTION_STRING)
.then(() => {
app.listen(8080);
const server = app.listen(8080);
const io = require('./socket').init(server, {
cors: {
origin: 'http://localhost:3000',
methods: ['GET', 'POST'],
},
});
io.on('connection', (socket) => {
console.log('client connected');
});
})
.catch((err) => console.log(err));
22 changes: 20 additions & 2 deletions controllers/feed.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { validationResult } = require('express-validator');
const io = require('../socket');
const Post = require('../models/post');
const User = require('../models/user');
const removeFile = require('../utils/removeFile');
Expand All @@ -11,6 +12,7 @@ exports.getPosts = async (req, res, next) => {
const totalItems = await Post.find().countDocuments();
const posts = await Post.find()
.populate('creator')
.sort({ createdAt: -1 })
.skip((currentPage - 1) * perPage)
.limit(perPage);

Expand Down Expand Up @@ -62,6 +64,11 @@ exports.createPost = async (req, res, next) => {
user.posts.push(post);
await user.save();

io.getIO().emit('posts', {
action: 'create',
post: { ...post.doc, creator: { _id: req.userId, name: user.name } },
});

res.status(201).json({
message: 'Post created successfully!',
post: post,
Expand Down Expand Up @@ -113,15 +120,15 @@ exports.updatePost = async (req, res, next) => {
const newContent = req.body.content;

try {
let post = await Post.findById(postId);
let post = await Post.findById(postId).populate('creator');

if (!post) {
const error = new Error('No post foound with the id: ' + postId);
error.statusCode = 404;
throw error;
}

if (post.creator.toString() !== req.userId) {
if (post.creator._id.toString() !== req.userId) {
const error = new Error('Not Authorized!');
error.statusCode = 403;
throw error;
Expand All @@ -136,6 +143,12 @@ exports.updatePost = async (req, res, next) => {
post.imageUrl = newImageUrl;

const updatedPost = await post.save();

io.getIO().emit('posts', {
action: 'update',
post: updatedPost,
});

res.status(200).json({ message: 'Post is updated', post: updatedPost });
} catch (err) {
if (!err.statusCode) {
Expand Down Expand Up @@ -179,6 +192,11 @@ exports.deletePost = async (req, res, next) => {

await user.save();

io.getIO().emit('posts', {
action: 'delete',
post: postId,
});

res.status(200).json({ message: 'Post is removed!' });
} catch (err) {
if (!err.statusCode) {
Expand Down
Loading

0 comments on commit 6edfb2c

Please sign in to comment.