Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added preClose hook to disconnect sockets #90

Merged
merged 3 commits into from
Aug 11, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
`fastify-socket.io` enables the use of [Socket.io](https://socket.io/) in a Fastify application.

Supports Fastify versions `4.x`
Supports socket.io version `4.x`

## Install

Expand Down Expand Up @@ -35,7 +36,19 @@ For more details see [examples](https://github.com/ducktors/fastify-socket.io/tr

You can use it as is without passing any option, or you can configure it as explained by Socket.io [doc](https://socket.io/docs/server-api/).

### Hook
### Hooks

By default the plugin will add a `preClose` hook that disconnects [all the local sockets](https://socket.io/docs/v4/server-api/#serverdisconnectsocketsclose) in order to close correctly the fastify server. In order to change this behaviour you can use `preClose` option:

```javascript
await fastify.register(require('fastify-socket.io'), {
preClose: (done) => {
// do other things
fastify.io.local.disconnectSockets(true);
done();
}
})
```

The plugin also adds an `onClose` hook which closes the socket server when the `fastify` instance is closed.

Expand Down
32 changes: 15 additions & 17 deletions examples/basic/server.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
const fastify = require("fastify");
const socketio = require("../..");
const { join } = require("path");
const { readFile } = require("fs").promises;
const fastify = require('fastify')
const socketio = require('../..')
const { join } = require('path')
const { readFile } = require('fs').promises

const app = fastify({ logger: true });
const app = fastify({ logger: true })

app.register(socketio);
app.register(socketio)

app.get("/", async (req, reply) => {
const data = await readFile(join(__dirname, "..", "index.html"));
reply.header("content-type", "text/html; charset=utf-8");
reply.send(data);
});
app.get('/', async (req, reply) => {
const data = await readFile(join(__dirname, '..', 'index.html'))
reply.header('content-type', 'text/html; charset=utf-8')
reply.send(data)
})
Dismissed Show dismissed Hide dismissed

app.ready((err) => {
if (err) throw err;
if (err) throw err

app.io.on("connect", (socket) =>
console.info("Socket connected!", socket.id)
);
});
app.io.on('connect', (socket) => console.info('Socket connected!', socket.id))
})

app.listen({ port: 3000 });
app.listen({ port: 3000 })
40 changes: 20 additions & 20 deletions examples/typescript-example/server.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
import fastify from "fastify";
import socketioServer from "../../src";
import { join } from "node:path";
import { readFile } from "node:fs/promises";
import { Server } from "socket.io";
import fastify from 'fastify'
import socketioServer from '../../src'
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'
import { Server } from 'socket.io'

const app = fastify({ logger: true });
const app = fastify({ logger: true })

app.register(socketioServer);
app.register(socketioServer)

app.get("/", async (_req, reply) => {
const data = await readFile(join(__dirname, "..", "index.html"));
reply.header("content-type", "text/html; charset=utf-8");
reply.send(data);
});
app.get('/', async (_req, reply) => {
const data = await readFile(join(__dirname, '..', 'index.html'))
reply.header('content-type', 'text/html; charset=utf-8')
reply.send(data)
})
Dismissed Show dismissed Hide dismissed

app.ready((err) => {
if (err) throw err;
if (err) throw err

app.io.on("connection", (socket: any) =>
console.info("Socket connected!", socket.id)
);
});
app.io.on('connection', (socket: any) =>
console.info('Socket connected!', socket.id),
)
})

app.listen({ port: 3000 });
app.listen({ port: 3000 })

declare module "fastify" {
declare module 'fastify' {
interface FastifyInstance {
io: Server<{ hello: string }>;
io: Server<{ hello: string }>
}
}
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"test:watch": "tsx --watch --test ./test/*.ts",
"test:coverage": "c8 --all --src src --reporter lcov --reporter text tsx --test ./test/*.ts"
},
"repository": {
"repository": {
"type": "git",
"url": "git+https://github.com/ducktors/fastify-socket.io.git"
},
Expand All @@ -33,7 +33,8 @@
"husky": "^8.0.3",
"lint-staged": "^13.2.3",
"rome": "11.0.0",
"socket.io": "^4.7.1",
"socket.io": "^4.7.4",
"socket.io-client": "^4.7.4",
alemagio marked this conversation as resolved.
Show resolved Hide resolved
"tsup": "^6.7.0",
"tsx": "^3.13.0",
"typescript": "^4.9.5"
Expand All @@ -42,6 +43,7 @@
"dist"
],
"peerDependencies": {
"fastify": "4.x.x"
"fastify": "4.x.x",
"socket.io": ">=4"
}
}
}
60 changes: 48 additions & 12 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

40 changes: 27 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,30 @@
import { FastifyInstance, FastifyPluginAsync } from "fastify";
import fp from "fastify-plugin";
import { Server, ServerOptions } from "socket.io";
import { FastifyInstance, FastifyPluginAsync } from 'fastify'
import fp from 'fastify-plugin'
import { Server, ServerOptions } from 'socket.io'

const fastifySocketIO: FastifyPluginAsync<Partial<ServerOptions>> = fp(
async function (fastify, opts) {
fastify.decorate("io", new Server(fastify.server, opts));
fastify.addHook("onClose", (fastify: FastifyInstance, done) => {
(fastify as any).io.close();
done();
});
export type FastifySocketioOptions = Partial<ServerOptions> & {
preClose?: (done: Function) => void
}

const fastifySocketIO: FastifyPluginAsync<FastifySocketioOptions> = fp(
async function (fastify, opts: FastifySocketioOptions) {
function defaultPreClose(done: Function) {
(fastify as any).io.local.disconnectSockets(true)
done()
}
fastify.decorate('io', new Server(fastify.server, opts))
fastify.addHook('preClose', (done) => {
if (opts.preClose) {
return opts.preClose(done)
}
return defaultPreClose(done)
})
fastify.addHook('onClose', (fastify: FastifyInstance, done) => {
(fastify as any).io.close()
done()
})
},
{ fastify: ">=4.x.x", name: "fastify-socket.io" }
);
{ fastify: '>=4.x.x', name: 'fastify-socket.io' },
)

export default fastifySocketIO;
export default fastifySocketIO
Loading
Loading