Chapter 23. Wiki: Markdown, Chat Subsite, Event Source
This chapter ties together a few different ideas. We’ll start with a chat subsite, which allows us to embed a chat widget on any page. We’ll use the HTML5 event source API to handle sending events from the server to the client. You can view the entire project on FP Haskell Center.
Subsite: Data
In order to define a subsite, we first need to create a foundation type for the subsite, the same as we would do for a normal Yesod application. In our case, we want to keep a channel of all the events to be sent to the individual participants of a chat. This ends up looking like:
-- @Chat/Data.hs
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module
Chat.Data
where
import
Blaze.ByteString.Builder.Char.Utf8
(
fromText
)
import
Control.Concurrent.Chan
import
Data.Monoid
((
<>
))
import
Data.Text
(
Text
)
import
Network.Wai.EventSource
import
Network.Wai.EventSource.EventStream
import
Yesod
-- | Our subsite foundation. We keep a channel of events that all connections
-- will share.
data
Chat
=
Chat
(
Chan
ServerEvent
)
We also need to define our subsite routes in the same module. We need to have two commands—one to send a new message to all users, and another to receive the stream of messages:
-- @Chat/Data.hs
mkYesodSubData
"Chat"
[
parseRoutes
|
/
send
SendR
POST
/
recv ...
Get Developing Web Apps with Haskell and Yesod, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.