Skip to content

Commit

Permalink
docs: improve example with express-session
Browse files Browse the repository at this point in the history
The example is now available with different syntaxes:

- CommonJS
- ES modules
- TypeScript

Related: #4787
  • Loading branch information
darrachequesne committed Sep 13, 2023
1 parent 8259cda commit d744fda
Show file tree
Hide file tree
Showing 10 changed files with 308 additions and 2 deletions.
File renamed without changes.
66 changes: 66 additions & 0 deletions examples/express-session-example/cjs/index.js
@@ -0,0 +1,66 @@
const express = require("express");
const { createServer } = require("node:http");
const { join } = require("node:path");
const { Server } = require("socket.io");
const session = require("express-session");

const port = process.env.PORT || 3000;

const app = express();
const httpServer = createServer(app);

const sessionMiddleware = session({
secret: "changeit",
resave: true,
saveUninitialized: true,
});

app.use(sessionMiddleware);

app.get("/", (req, res) => {
res.sendFile(join(__dirname, "index.html"));
});

app.post("/incr", (req, res) => {
const session = req.session;
session.count = (session.count || 0) + 1;
res.status(200).end("" + session.count);

io.to(session.id).emit("current count", session.count);
});

app.post("/logout", (req, res) => {
const sessionId = req.session.id;
req.session.destroy(() => {
// disconnect all Socket.IO connections linked to this session ID
io.to(sessionId).disconnectSockets();
res.status(204).end();
});
});

const io = new Server(httpServer);

io.engine.use(sessionMiddleware);

io.on("connection", (socket) => {
const req = socket.request;

socket.join(req.session.id);

socket.on("incr", (cb) => {
req.session.reload((err) => {
if (err) {
// session has expired
return socket.disconnect();
}
req.session.count = (req.session.count || 0) + 1;
req.session.save(() => {
cb(req.session.count);
});
});
});
});

httpServer.listen(port, () => {
console.log(`application is running at: http://localhost:${port}`);
});
15 changes: 15 additions & 0 deletions examples/express-session-example/cjs/package.json
@@ -0,0 +1,15 @@
{
"name": "express-session-example",
"version": "0.0.1",
"private": true,
"type": "commonjs",
"description": "Example with express-session (https://github.com/expressjs/session)",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "~4.17.3",
"express-session": "~1.17.2",
"socket.io": "^4.7.2"
}
}
61 changes: 61 additions & 0 deletions examples/express-session-example/esm/index.html
@@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Example with express-session</title>
</head>
<body>
<button onclick="incrementWithFetch()">Increment with fetch()</button>
<button onclick="logout()">Logout</button>
<p>Count: <span id="httpCount">0</span></p>

<button onclick="incrementWithEmit()">
Increment with Socket.IO emit()
</button>
<p>Status: <span id="ioStatus">disconnected</span></p>
<p>Count: <span id="ioCount">0</span></p>

<script src="/socket.io/socket.io.js"></script>
<script>
const httpCount = document.getElementById("httpCount");
const ioStatus = document.getElementById("ioStatus");
const ioCount = document.getElementById("ioCount");

const socket = io({
// with WebSocket only
// transports: ["websocket"],
});

async function incrementWithFetch() {
const response = await fetch("/incr", {
method: "post",
});
httpCount.innerText = await response.text();
}

function logout() {
fetch("/logout", {
method: "post",
});
}

async function incrementWithEmit() {
socket.emit("incr", (count) => {
ioCount.innerText = count;
});
}

socket.on("connect", () => {
ioStatus.innerText = "connected";
});

socket.on("disconnect", () => {
ioStatus.innerText = "disconnected";
});

socket.on("current count", (count) => {
ioCount.innerText = count;
});
</script>
</body>
</html>
@@ -1,5 +1,5 @@
import express from "express";
import { createServer } from "http";
import { createServer } from "node:http";
import { Server } from "socket.io";
import session from "express-session";

Expand All @@ -17,7 +17,7 @@ const sessionMiddleware = session({
app.use(sessionMiddleware);

app.get("/", (req, res) => {
res.sendFile("./index.html", { root: process.cwd() });
res.sendFile(new URL("./index.html", import.meta.url).pathname);
});

app.post("/incr", (req, res) => {
Expand Down
61 changes: 61 additions & 0 deletions examples/express-session-example/ts/index.html
@@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Example with express-session</title>
</head>
<body>
<button onclick="incrementWithFetch()">Increment with fetch()</button>
<button onclick="logout()">Logout</button>
<p>Count: <span id="httpCount">0</span></p>

<button onclick="incrementWithEmit()">
Increment with Socket.IO emit()
</button>
<p>Status: <span id="ioStatus">disconnected</span></p>
<p>Count: <span id="ioCount">0</span></p>

<script src="/socket.io/socket.io.js"></script>
<script>
const httpCount = document.getElementById("httpCount");
const ioStatus = document.getElementById("ioStatus");
const ioCount = document.getElementById("ioCount");

const socket = io({
// with WebSocket only
// transports: ["websocket"],
});

async function incrementWithFetch() {
const response = await fetch("/incr", {
method: "post",
});
httpCount.innerText = await response.text();
}

function logout() {
fetch("/logout", {
method: "post",
});
}

async function incrementWithEmit() {
socket.emit("incr", (count) => {
ioCount.innerText = count;
});
}

socket.on("connect", () => {
ioStatus.innerText = "connected";
});

socket.on("disconnect", () => {
ioStatus.innerText = "disconnected";
});

socket.on("current count", (count) => {
ioCount.innerText = count;
});
</script>
</body>
</html>
72 changes: 72 additions & 0 deletions examples/express-session-example/ts/index.ts
@@ -0,0 +1,72 @@
import express = require("express");
import { createServer } from "http";
import { Server } from "socket.io";
import session from "express-session";
import { type Request } from "express";

declare module "express-session" {
interface SessionData {
count: number;
}
}

const port = process.env.PORT || 3000;

const app = express();
const httpServer = createServer(app);

const sessionMiddleware = session({
secret: "changeit",
resave: true,
saveUninitialized: true,
});

app.use(sessionMiddleware);

app.get("/", (req, res) => {
res.sendFile(new URL("./index.html", import.meta.url).pathname);
});

app.post("/incr", (req, res) => {
const session = req.session;
session.count = (session.count || 0) + 1;
res.status(200).end("" + session.count);

io.to(session.id).emit("current count", session.count);
});

app.post("/logout", (req, res) => {
const sessionId = req.session.id;
req.session.destroy(() => {
// disconnect all Socket.IO connections linked to this session ID
io.to(sessionId).disconnectSockets();
res.status(204).end();
});
});

const io = new Server(httpServer);

io.engine.use(sessionMiddleware);

io.on("connection", (socket) => {
const req = socket.request as Request;

socket.join(req.session.id);

socket.on("incr", (cb) => {
req.session.reload((err) => {
if (err) {
// session has expired
return socket.disconnect();
}
req.session.count = (req.session.count || 0) + 1;
req.session.save(() => {
cb(req.session.count);
});
});
});
});

httpServer.listen(port, () => {
console.log(`application is running at: http://localhost:${port}`);
});
20 changes: 20 additions & 0 deletions examples/express-session-example/ts/package.json
@@ -0,0 +1,20 @@
{
"name": "express-session-example",
"version": "0.0.1",
"private": true,
"type": "module",
"description": "Example with express-session (https://github.com/expressjs/session)",
"scripts": {
"start": "ts-node index.ts"
},
"dependencies": {
"@types/express": "^4.17.17",
"@types/express-session": "^1.17.7",
"@types/node": "^20.6.0",
"express": "~4.17.3",
"express-session": "~1.17.2",
"socket.io": "^4.7.2",
"ts-node": "^10.9.1",
"typescript": "^5.2.2"
}
}
11 changes: 11 additions & 0 deletions examples/express-session-example/ts/tsconfig.json
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2022",
"strict": true
},
"ts-node": {
"esm": true
}
}

0 comments on commit d744fda

Please sign in to comment.