如何在Node中的Mongoose保存上触发套接字事件?

时间:2019-03-18 10:01:15

标签: node.js mongoose socket.io

这是我的模特。

const mongoose = require('mongoose');
var timestamps = require('mongoose-timestamp');

var CategorySchema = new mongoose.Schema({
    name: String
});

CategorySchema.plugin(timestamps);
CategorySchema.post('save', function () {
    console.log(this.name);
  });
var Category = mongoose.model('Category', CategorySchema);

module.exports = Category;

这是我的index.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const { mongoose } = require('./config/db.js');
var routes = require('./routes/routes');
var j = require('./utility/mailer');
var app = express();

//app.use(bodyParser.json());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));

app.use(cors({ origin: 'http://localhost:4200' }));
app.use(express.static('uploads'));
//app.listen(3000, () => console.log('server started'));
app.use(function (req, res, next) {
    res.setTimeout(10000, function () {
        console.log('timeout call');
        res.status(408).send({ 'res': 'timed out' });
        //res.end(408);
        return;
    });
    next();
});
app.use('/', routes);

app.set("port", (process.env.PORT || 3000));
/*
app.listen(app.get("port"), function () {
 console.log("Server started: http://localhost:" + app.get("port") + "/");
}) */
var server = app.listen(app.get('port'), function () {
    console.log('Express server listening on port ' + server.address().port);
});


var io = require("socket.io").listen(server, {
    handlePreflightRequest: (req, res) => {
        const headers = {
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
            "Access-Control-Allow-Origin": req.headers.origin,
            "Access-Control-Allow-Credentials": true
        };
        res.writeHead(200, headers);
        res.end();
    }
});

let timerId = null,
    sockets = new Set();
io.on('connection', socket => {
    console.log('connected');
    sockets.add(socket);
    console.log(`Socket ${socket.id} added`);

    if (!timerId) {
        startTimer();
    }

       socket.emit('new data', { data: 'new data'});
    socket.on('clientdata', data => {
    });



    socket.on('disconnect', () => {
    });

});
function startTimer() {
    timerId = setInterval(() => {
        if (!sockets.size) {
            clearInterval(timerId);
            timerId = null;;
        }
        for (const s of sockets) {
            s.emit('data', { data: 'some data' });
        }

    }, 2000);
}
var gulp = require('gulp');
var sonarqubeScanner = require('sonarqube-scanner');

gulp.task('default', function (callback) {
    sonarqubeScanner({
        serverUrl: "https://localhost:8081",
    }, callback);
});
io.listen(8000);

我想触发类别模型文件中猫鼬保存钩子内套接字的事件。您能建议一种方法吗?挂钩正在工作。但是我无法找出一种可能从socket.on触发事件的方法,因为它在index.js中。

如果您不将计时器放在那里,那很好。就像我按照教程讲的那样,那只是为了在一定间隔内发出事件。

1 个答案:

答案 0 :(得分:1)

您可以将IO设置为全局变量,以便可以在应用程序的任何位置访问它。

global.io = require("socket.io").listen(server, {
handlePreflightRequest: (req, res) => {
    const headers = {
        "Access-Control-Allow-Headers": "Content-Type, Authorization",
        "Access-Control-Allow-Origin": req.headers.origin,
        "Access-Control-Allow-Credentials": true
    };
    res.writeHead(200, headers);
    res.end();
}});

然后在您的保存钩子中

io.emit("event-name",payload);