3d62bd80ff1c41c7eba0391e57e5cd754db5c03d — Thomas Letan 1 year, 1 month ago 0674d38
refactor: Simplify the `get-player` function

The previous function was basically taking care of two different
things: (1) an asynchronous HTTP request, and (2) JSON parsing. This
patch divides this function into three, more focus simpler ones. As a
result, it is both more readable, and potentially easier to turn into
a reusable macro for future backend functions.

Signed-off-by: Thomas Letan <contact@thomasletan.fr>
1 files changed, 15 insertions(+), 14 deletions(-)

M backend.lisp
M backend.lisp => backend.lisp +15 -14
@@ 16,31 16,32 @@   (defpackage :lycan/backend
    (:nicknames :lb)
-   (:use :cl :alexandria)
+   (:use :cl :alexandria :flexi-streams)
    (:export get-player))
  
  (cl:in-package :lycan/backend)
  
  (defclass player ()
-   ((name :initarg :name
-          :initform (error "must have a name")
-          :accessor name)
-    (characters :initarg :characters
+   ((characters :initarg :characters
                 :initform nil
                 :accessor characters)))
  
+ (defun get-player-url (name)
+   (concatenate 'string "http://0.0.0.0:4001/player/" name))
+ 
  (defun get-player (name &key then event-cb)
    (if then
        (blackbird:catcher
         (blackbird:multiple-promise-bind (body status)
-            (das:http-request (concatenate 'string "http://0.0.0.0:4001/player/" name))
+            (das:http-request (get-player-url name))
           (if (eq status 200)
-              (let* ((json-str (flexi-streams:octets-to-string body
-                                                               :external-format :utf-8))
-                     (json (jsown:parse json-str))
-                     (pl (make-instance 'player :name (jsown:val json "name"))))
-                (funcall then pl))))
+              (funcall then (byte-array-to-player body))))
         (error (e)
-               (if event-cb
-                   (funcall event-cb e))))
-       (error "need to provide a callback to use the result"))))
+               (when event-cb
+                 (funcall event-cb e))))
+       (error "need to provide a callback to use the result")))
+ 
+ (defun byte-array-to-player (bytes)
+   (let* ((json-str (octets-to-string bytes :external-format :utf-8))
+          (json (jsown:parse json-str)))
+     (make-instance 'player :characters (jsown:val json "characters"))))