Skip to content

Commit 42c56eb

Browse files
mcollinaairhorns
authored andcommitted
Ensure websocket handler types are only applied to websocket handlers
This corrects an issue introduced in #64 where upon adding `fastify-websocket` to a project all route handlers were (accidentally) assumed to be websocket handlers getting the different (and decidedly less useful) types. My bad! This corrects the issue by using a type-land overload of the RouteShorthand function definition to change the type of the handler only if the handler is in fact `{ websocket: true }`. Also adds tests, `tsd` is handy!
1 parent f8ad6c6 commit 42c56eb

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

index.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ declare module 'fastify' {
2323
> {
2424
<RequestGeneric extends RequestGenericInterface = RequestGenericInterface, ContextConfig = ContextConfigDefault>(
2525
path: string,
26-
opts: RouteShorthandOptions<RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>,
26+
opts: RouteShorthandOptions<RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig> & { websocket: true }, // this creates an overload that only applies these different types if the handler is for websockets
2727
handler?: WebsocketHandler
2828
): FastifyInstance<RawServer, RawRequest, RawReply>;
2929
}

test/types/index.test-d.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import wsPlugin, { SocketStream } from '../..';
2-
import fastify, { WebsocketHandler, FastifyRequest, FastifyInstance, RequestGenericInterface } from 'fastify';
2+
import fastify, { WebsocketHandler, FastifyRequest, FastifyInstance, RequestGenericInterface, FastifyReply } from 'fastify';
33
import { expectType } from 'tsd';
44
import { Server as HttpServer, IncomingMessage } from 'http'
55
import { Server } from 'ws';
@@ -15,14 +15,20 @@ app.register(wsPlugin, {
1515
});
1616
app.register(wsPlugin, { options: { perMessageDeflate: true } });
1717

18-
app.get('/', { websocket: true }, function perRouteHandler(
19-
connection: SocketStream,
20-
req: IncomingMessage,
21-
params
22-
) {
18+
app.get('/websockets', { websocket: true }, async function(connection, req, params) {
2319
expectType<FastifyInstance>(this);
2420
expectType<SocketStream>(connection);
2521
expectType<Server>(app.websocketServer);
2622
expectType<IncomingMessage>(req)
2723
expectType<{ [key: string]: any } | undefined>(params);
2824
});
25+
26+
app.get('/not-specifed', async (request, reply) => {
27+
expectType<FastifyRequest>(request);
28+
expectType<FastifyReply>(reply)
29+
});
30+
31+
app.get('/not-websockets', { websocket: false }, async (request, reply) => {
32+
expectType<FastifyRequest>(request);
33+
expectType<FastifyReply>(reply);
34+
});

0 commit comments

Comments
 (0)