Skip to content

Instantly share code, notes, and snippets.

@YonathanMeguira
Created August 31, 2018 06:11
Show Gist options
  • Save YonathanMeguira/eaa53201f53f331bac4fc885cfc8e2a3 to your computer and use it in GitHub Desktop.
Save YonathanMeguira/eaa53201f53f331bac4fc885cfc8e2a3 to your computer and use it in GitHub Desktop.
websocket socket.io
const express = require("express");
const socketio = require("socket.io");
const _ = require("lodash");
const actions = require("./actions");
const port = process.env.PORT || 5000;
const env = process.env.NODE_ENV || "development";
const app = express();
app.set("port", port);
app.set("env", env);
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
const router = express.Router(); // get an instance of the express Router
router.get("/", (req, res) => {
res.json({health: "OK", ...db});
});
app.use("/", router);
const server = app.listen(app.get("port"), () => {
console.log("SocketIO server listening on port " + app.get("port"));
});
const io = socketio(server, {origins: "*:*"});
const body = `It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).`
const db = {
notes: {
1: {id: 1, author: "First Article", body},
2: {id: 2, author: "Second Article", body},
3: {id: 3, author: "Third Article", body}
}
};
const updateNote = noteData => {
const note = db.notes[noteData.id];
if (note) {
db.notes[noteData.id] = _.merge(note, noteData);
return db.notes[noteData.id];
} else return undefined;
};
const deleteNote = id => {
if (db.notes[id]) {
delete db.notes[id];
}
return id;
};
io.on("connection", client => {
client.on(actions.ADD_NOTE, note => {
db.notes[note.id] = note;
});
client.on(actions.LIST_NOTES, () => {
client.emit(actions.NOTES_LISTED, db.notes);
});
client.on(actions.UPDATE_NOTE, note => {
updateNote(note);
});
client.on(actions.DELETE_NOTE, id => {
deleteNote(id);
});
client.on("disconnect", () => {
console.log("client disconnected");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment