-
Notifications
You must be signed in to change notification settings - Fork 3
/
Example.re
64 lines (50 loc) · 1.79 KB
/
Example.re
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Describe your socket params type
type example = {username: string};
let socket =
Socket.make(
"/socket",
Some(Socket.options(~transport=`longpoll, ~params={username: "test"}, ())),
);
let _ = Socket.onOpen(socket, () => {Js.log("Socket connection open.")});
let _ = Socket.onClose(socket, () => {Js.log("Socket was closed.")});
let _ = Socket.connect(socket);
let channel = socket -> Channel.make("test", Js.Obj.empty());
let _ =
channel
->Channel.join(~timeout=1000, ())
->Push.receive(~status="ok", ~callback=params => {Js.log(params)})
->Push.receive(~status="error", ~callback=params => {Js.log(params)});
let _ = channel->Channel.push(~event="test", ~payload=Js.Obj.empty(), ());
/**
Create a module with a type t
This should describe your presence payload, as it is in your server
Plus a phx_ref that is sent by default by Phoenix
i.e., if you have this in your server;
Presence.track(socket, socket.assigns.user.id, %{
id: socket.assigns.user.id, => integer
name: socket.assigns.user.name => string
})
You use the following module:
*/
module PresenceObject = {
type t = {
phx_ref: string,
id: int,
name: string,
};
};
// Create a Presence module that expects to receive your record as its payload
module PresenceMod = Presence.MakeModule(PresenceObject);
let presence = PresenceMod.make(channel, None);
open PresenceMod;
presence->onJoin((~id, ~currentPresence, ~newPresence) => {
Js.log(id);
switch (unwrap(currentPresence), unwrap(newPresence)) {
| (None, None) => Js.log("No presences!")
| (None, Some({id: userId, phx_ref: _})) =>
Js.log({j|New user: $userId|j})
| (Some({id: userId, phx_ref}), Some(_)) =>
Js.log({j| User $userId logged from a new device: $phx_ref"|j})
| _ => Js.log("Something ins very, very wrong around here.")
};
});