Sử dụng broadcast private reverb với nextjs
Đôi khi chúng ta cần sử dụng private để chuyển broadcast từ server đến người dùng cụ thể .
Đầu tiên mình cần tạo broadcast :
<?php
namespace App\Events\Broadcast;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PrivateBroadcast implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*/
public function __construct(public $data)
{
//
}
/**
* Get the channels the event should broadcast on.
*
* @return array<int, Channel>
*/
public function broadcastOn(): array
{
return [
new PrivateChannel('user.1'),
];
}
public function broadcastWith(): array
{
return [
'id' => $this->data['id'],
'body' => $this->data['body'],
];
}
public function broadcastAs(): string
{
return 'comment.created';
}
}
Tiếp theo mình cần tạo đầu auth với router/api.php :
Route::post('/broadcast/auth', [\App\Http\Controllers\Apiv1\AuthController::class, 'broadcastauth'])->middleware(['auth:api']);
Ở đây cần xác thực dữ liệu với auth:api
Tiếp theo cần controller như sau :
use Illuminate\Support\Facades\Broadcast;
public function broadcastauth(Request $request)
{
Log::info(Auth::id());
Log::info($request);
return Broadcast::auth($request);
}
Tiếp theo chúng ta vào router/channel.php như sau :
Broadcast::channel('user.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Thế là xong phần server giờ chúng ta đến phần nextjs
Đầu tiên cần tạo libs/echo.tsx
import Echo from "laravel-echo";
import Pusher from "pusher-js";
let echo: Echo | null = null;
if (typeof window !== "undefined") {
(window as any).Pusher = Pusher;
console.log(localStorage.getItem("token"));
echo = new Echo({
broadcaster: "reverb",
key: process.env.NEXT_PUBLIC_REVERB_APP_KEY!,
wsHost: process.env.NEXT_PUBLIC_REVERB_HOST!,
wsPort: 443,
wssPort: 443,
forceTLS: true,
enabledTransports: ["ws", "wss"],
authEndpoint: process.env.NEXT_PUBLIC_API_URL + "broadcast/auth",
auth: {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
Accept: "application/json",
},
},
});
}
export default echo;
Tiếp theo cần sử dụng effect như sau
useEffect(() => {
const channel = echo.private("user.5");
channel.listen(".comment.created", (event: any) => {
console.log("Nhận được:", event);
console.log(event.id);
console.log(event.body);
setThongtin((prev) => [
{
id: event.id,
body: event.body,
},
...prev,
]);
});
return () => {
echo.leaveChannel("post.1");
};
}, []);
Giờ chúng ta đã có thể gửi private đến người dùng