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) (in-package :remote-snake-server-api)
(defclass api () (defclass api ()
((gm ((gm
:initform (make-instance 'game-manager)))) :initform (make-instance 'game-manager))))
;;; Parse the request and return it as a plist
;;; TODO: Handle errors (valid json etc..)
(defun parse-request (request) (defun parse-request (request)
(flet ((normalizer (key) (flet ((normalizer (key) (string-upcase key)))
(string-upcase key))) (let* ((p-request (parse request :normalize-all t :keyword-normalizer #'normalizer ))
(let ((p-request (parse request :normalize-all t :keyword-normalizer #'normalizer ))) (type (getf p-request :type :not-found)))
p-request))) (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) (defmethod handle-new-game ((api api) data)
(with-slots (gm) api (with-slots (gm) api
@ -22,7 +37,6 @@
(to-json (to-json
(append (list :type "state") game-dump)))))) (append (list :type "state") game-dump))))))
;;; TODO: RETURN JSON !!!!
(defmethod handle-update ((api api) data) (defmethod handle-update ((api api) data)
(with-slots (gm) api (with-slots (gm) api
(let* ((dir (getf data :direction)) (let* ((dir (getf data :direction))
@ -37,10 +51,9 @@
(if dir (if dir
(refresh game :dir dir) (refresh game :dir dir)
(refresh game)) (refresh game))
(append (list :type "update") (dump gm game-id))))) (append (list :type "state") (dump gm game-id)))))
(defmethod handle-request ((api api) request) (defmethod handle-request ((api api) request)
(let* ((data (parse-request request)) (let* ((data (parse-request request))
(type (getf data :type))) (type (getf data :type)))