Almost finish API

This commit is contained in:
Loic Guegan 2019-05-10 12:30:40 +02:00
parent 7d68338dff
commit 284ad037a5

View file

@ -1,18 +1,33 @@
(in-package :remote-snake-server-api)
(defclass api ()
((gm
:initform (make-instance 'game-manager))))
;;; TODO: Handle errors (valid json etc..)
;;; Parse the request and return it as a plist
(defun parse-request (request)
(flet ((normalizer (key)
(string-upcase key)))
(let ((p-request (parse request :normalize-all t :keyword-normalizer #'normalizer )))
p-request)))
(flet ((normalizer (key) (string-upcase key)))
(let* ((p-request (parse request :normalize-all t :keyword-normalizer #'normalizer ))
(type (getf p-request :type :not-found)))
(cond
((eq type :not-found)
(error "Invalid request: Bad request type"))
((equal type "update")
(progn
(unless (getf p-request :game-id) (error "Invalid request: No game id"))
(let ((dir (getf p-request :direction :not-found)))
(when (eq :not-found dir) (error "Invalid request: No snake direction provided"))
(unless (or (equal "up" dir) (equal "down" dir) (equal "left" dir) (equal "right" dir) (eq nil dir)) (error "Invalid request: Bad direction"))
(cond
((equal dir "up") (setf (getf p-request :direction) :up))
((equal dir "down") (setf (getf p-request :direction) :down))
((equal dir "left") (setf (getf p-request :direction) :left))
((equal dir "right") (setf (getf p-request :direction) :right))))))
((not (equal type "new-game"))
(error "Invalid request: Unknow request type")))
p-request)))
(defmethod handle-new-game ((api api) data)
(with-slots (gm) api
@ -22,7 +37,6 @@
(to-json
(append (list :type "state") game-dump))))))
;;; TODO: RETURN JSON !!!!
(defmethod handle-update ((api api) data)
(with-slots (gm) api
(let* ((dir (getf data :direction))
@ -37,10 +51,9 @@
(if dir
(refresh game :dir dir)
(refresh game))
(append (list :type "update") (dump gm game-id)))))
(append (list :type "state") (dump gm game-id)))))
(defmethod handle-request ((api api) request)
(let* ((data (parse-request request))
(type (getf data :type)))