jdx / mean-sample

Sample project for Write Modern Web Apps with the MEAN Stack by Jeff Dickey
https://mean-sample.herokuapp.com
166 stars 90 forks source link

Pubsub.js not working #17

Closed mchavezi closed 9 years ago

mchavezi commented 9 years ago

I am on page 138 of the printed book.

I am getting this error:

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED
    at RedisClient.on_error (/Applications/MAMP/htdocs/Ignitor/node_modules/redis/index.js:196:24)
    at Socket. (/Applications/MAMP/htdocs/Ignitor/node_modules/redis/index.js:106:14)
    at Socket.emit (events.js:107:17)
    at net.js:451:14
    at process._tickCallback (node.js:355:11)

This is how posts.js looks:

var Post = require('../../models/post')
var router = require('express').Router()
var websockets = require('../../websockets')
var pubsub = require('../../pubsub')

router.get('/', function (req, res, next) {
  Post.find() 
  .sort('-date')
  .exec(function(err, posts) {
    if (err) { return next(err) }
    res.json(posts)
  })
})

router.post('/', function (req, res, next) {
  var post = new Post({body: req.body.body})
  post.username = req.auth.username
  post.save(function (err, post) {
    if (err) { return next(err) }
    pubsub.publish('new_post', post)
    res.status(201).json(post)
  })
})

pubsub.subscribe('new_post', function (post) {
  websockets.broadcast('new_post', post)
})

module.exports = router

and how pubsub.js looks like:

var redis = require('redis')
var client = redis.createClient()
exports.publish = function (topic, data) {
    client.publish(topic, JSON.stringify(data))
}
exports.subscribe = function (topic, cb) {
    var client = redis.createClient()
    client.subscribe(topic)
    client.on('message', function (channel, message) {
        cb(JSON.parse(message))
    })
}

I installed redis with:

npm install redis --save

Is this the right one to use?

Do I need to start the redis server or something?

Any tips greatly appreciated.

Great book!

mchavezi commented 9 years ago

OK I figured it out. Had to

brew install redis

and then

redis-server

Onward ho!