From 284ad037a5fd014fbcd08e1b8fc8d039e623f49d Mon Sep 17 00:00:00 2001 From: Loic Guegan Date: Fri, 10 May 2019 12:30:40 +0200 Subject: [PATCH] Almost finish API --- server/api/api.lisp | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/server/api/api.lisp b/server/api/api.lisp index 9174717..5a67f06 100644 --- a/server/api/api.lisp +++ b/server/api/api.lisp @@ -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)))