使用Scotty的Haskell REST服务:将JSON转换回数据

时间:2016-08-02 09:56:56

标签: json haskell scotty

我使用Haskell和Scotty构建了一个REST服务,并且具有以下代码:

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}

module Main where

import Data.Monoid ((<>))
import Data.Aeson (FromJSON, ToJSON)
import Data.Text.Lazy
import GHC.Generics
import Web.Scotty

data Point = Point { x :: Int, y :: Int } deriving (Generic, Show)
instance ToJSON Point
instance FromJSON Point
movePoint :: Point -> Int -> Int -> Point
movePoint (Point x y) dx dy = Point (x + dx) (y + dy)

data Rectangle = Rectangle { width :: Int, height :: Int, point :: Point } deriving (Generic, Show)
instance ToJSON Rectangle
instance FromJSON Rectangle
move :: Rectangle -> Int -> Int -> Rectangle
move r@(Rectangle {point = p}) dx dy = r { point = movePoint p dx dy }

main = do
  putStrLn "Starting Server..."
  scotty 3000 $ do
    get "/rectangle/:id" $ do
      id <- param "id"      
      text id

    post "/rectangle" $ do
      rectangle <- jsonData :: ActionM Rectangle
      json rectangle    

    post "rectangle/move/:dx/:dy" $ do      
      dx <- param "dx"
      dy <- param "dy"
      rectangle <- jsonData :: ActionM Rectangle
      move rectangle dx dy
      json rectangle

编译时我收到此错误:

Couldn't match expected type `Web.Scotty.Internal.Types.ActionT
                                    Text IO a0'
                with actual type `Rectangle'
    In a stmt of a 'do' block: move rectangle dx dy
    In the second argument of `($)', namely
      `do { dx <- param "dx";
            dy <- param "dy";
            rectangle <- jsonData :: ActionM Rectangle;
            move rectangle dx dy;
            .... }'

我缺少什么?我想调用“移动”功能,然后将移动的矩形发回...

0 个答案:

没有答案