Skip to content

Commit 62c4c2c

Browse files
committed
Add websocket/longpoll macro
1 parent d6a715d commit 62c4c2c

File tree

2 files changed

+37
-16
lines changed

2 files changed

+37
-16
lines changed

lib/phoenix/socket/router.ex

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,7 @@ defmodule Phoenix.Socket.Router do
1212
path = Path.join(path, end_segment)
1313

1414
quote do
15-
match :*,
16-
unquote(path),
17-
Phoenix.Transports.WebSocket,
18-
[
19-
{:user_socket, unquote(user_socket)}
20-
| unquote(websocket)
21-
]
15+
websocket unquote(path), unquote(user_socket), unquote(websocket)
2216
end
2317
else
2418
[]
@@ -31,13 +25,7 @@ defmodule Phoenix.Socket.Router do
3125
path = Path.join(path, end_segment)
3226

3327
quote do
34-
match :*,
35-
unquote(path),
36-
Phoenix.Transports.LongPoll,
37-
[
38-
{:user_socket, unquote(user_socket)}
39-
| unquote(longpoll)
40-
]
28+
longpoll unquote(path), unquote(user_socket), unquote(longpoll)
4129
end
4230
else
4331
[]
@@ -49,6 +37,30 @@ defmodule Phoenix.Socket.Router do
4937
end
5038
end
5139

40+
defmacro websocket(path, user_socket, opts \\ []) do
41+
quote do
42+
match :*,
43+
unquote(path),
44+
Phoenix.Transports.WebSocket,
45+
[
46+
{:user_socket, unquote(user_socket)}
47+
| unquote(opts)
48+
]
49+
end
50+
end
51+
52+
defmacro longpoll(path, user_socket, opts \\ []) do
53+
quote do
54+
match :*,
55+
unquote(path),
56+
Phoenix.Transports.LongPoll,
57+
[
58+
{:user_socket, unquote(user_socket)}
59+
| unquote(opts)
60+
]
61+
end
62+
end
63+
5264
defp put_auth_token(true, enabled), do: [auth_token: enabled]
5365
defp put_auth_token(opts, enabled), do: Keyword.put(opts, :auth_token, enabled)
5466
end

test/phoenix/integration/websocket_socket_test.exs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,18 @@ defmodule Phoenix.Integration.WebSocketTest do
100100
#
101101
# match :*, "/longpoll", Phoenix.Transports.LongPoll, user_socket: UserSocket
102102
# end
103+
#
104+
#
105+
103106

104-
socket "/ws", UserSocket,
105-
websocket: [check_origin: ["//example.com"], subprotocols: ["sip"], timeout: 200]
107+
# socket "/ws", UserSocket,
108+
# websocket: [check_origin: ["//example.com"], subprotocols: ["sip"], timeout: 200]
109+
scope "/ws" do
110+
websocket "/websocket", UserSocket,
111+
check_origin: ["//example.com"], subprotocols: ["sip"], timeout: 200
112+
113+
longpoll "/longpoll", UserSocket
114+
end
106115

107116
socket "/custom/some_path", UserSocket,
108117
websocket: [path: "nested/path", check_origin: ["//example.com"], timeout: 200]

0 commit comments

Comments
 (0)