git.iko.soy/rowtype-yoga/purescript-yoga-fetch-om
on main help sign in
70 lines 2.4 kB history raw
1module Polymorphic.Spec where
3import Prelude
5import Effect.Aff (bracket)
6import Effect.Aff.Class (liftAff)
7import Effect.Class (liftEffect)
8import Test.Spec (Spec, around, describe, it)
9import Test.Spec.Assertions (shouldEqual)
10import Yoga.Fastify.Fastify as F
11import Yoga.Fastify.Fastify (Port(..), Host(..))
12import Yoga.Fastify.Om.API (registerAPI)
13import Yoga.Fastify.Om.Route (Handler, handle, respond)
14import Yoga.Fetch.Om (GET, Route, type (/), type (:), client)
15import Yoga.Om (ask, runOm)
16import Control.Monad.Error.Class (throwError)
18type User = { id :: Int, name :: String }
20type GetUserRoute = Route GET ("users" / "id" : Int) {} (ok :: { body :: User })
22type TestAPI =
23 { getUser :: GetUserRoute
24 }
26api = client @TestAPI "http://localhost:44931"
28spec :: Spec Unit
29spec = around withServer $ describe "polymorphic client" do
30 it "fetches user with { token :: String } context" \_ ->
31 runOm { token: "secret123" } { exception: throwError } do
32 { token } <- ask
33 { name } <- api.getUser { id: 42 }
34 liftAff $ (token <> ":" <> name) `shouldEqual` "secret123:User 42"
36 it "fetches user with { apiKey :: String, userId :: Int } context" \_ ->
37 runOm { apiKey: "mykey", userId: 7 } { exception: throwError } do
38 { apiKey, userId } <- ask
39 { name } <- api.getUser { id: userId }
40 liftAff $ (apiKey <> ":" <> name) `shouldEqual` "mykey:User 7"
42 it "same api.getUser works in two different contexts" \_ -> do
44 runOm { token: "tok1" } { exception: throwError } do
45 { token } <- ask
46 { name } <- api.getUser { id: 1 }
47 liftAff $ (token <> ":" <> name) `shouldEqual` "tok1:User 1"
49 runOm { endpoint: "prod", region: "eu" } { exception: throwError } do
50 { endpoint, region } <- ask
51 { name } <- api.getUser { id: 2 }
52 liftAff $ (endpoint <> "-" <> region <> ":" <> name) `shouldEqual` "prod-eu:User 2"
54withServer :: forall a. (Unit -> _ a) -> _ a
55withServer test = bracket acquire release (\_ -> test unit)
56 where
57 acquire = do
58 fastify <- liftEffect do
59 f <- F.fastify {}
60 registerAPI @TestAPI { getUser: getUserHandler } f
61 pure f
62 void $ F.listen { port: Port 44931, host: Host "0.0.0.0" } fastify
63 pure fastify
65 release = F.close
67getUserHandler :: Handler GetUserRoute ()
68getUserHandler = handle do
69 { path } <- ask
70 respond @"ok" { id: path.id, name: "User " <> show path.id }