diff --git a/src/main.lisp b/src/main.lisp index f5a5b53..839dc49 100644 --- a/src/main.lisp +++ b/src/main.lisp @@ -11,7 +11,8 @@ #:parse) (:import-from #:dexador #:request - #:http-request-failed) + #:http-request-failed + #:response-status) (:import-from #:quri #:make-uri #:render-uri) @@ -26,30 +27,31 @@ (defparameter *api-key* nil) (defparameter *service-domain* nil) -(defun %request (method endpoint &optional (path "") (query nil) (content nil)) +(defun %request (method endpoint &optional path query content) + (or *service-domain* (error "microcms:*service-domain* is not configured.")) + (or *api-key* (error "microcms:*api-key* is not configured.")) (let* ((url (%build-uri endpoint path query)) - (headers `(("X-MICROCMS-API-KEY" . ,*api-key*) - ("Content-Type" . "application/json")))) - (format t "API request url: ~a~%" url) + (req-headers `(("X-MICROCMS-API-KEY" . ,*api-key*) + ("Content-Type" . "application/json")))) (handler-case - (multiple-value-bind (res-body status resp-headers) + (multiple-value-bind (res-body status res-headers) (request url :method method - :headers headers + :headers req-headers :content (and content (to-json content)) :force-binary nil) - (format t "API response status: ~a~%" status) + (format t "microCMS status: ~D~%" status) (when (and (stringp res-body) - (search "application/json" (gethash "content-type" resp-headers))) + (search "application/json" (gethash "content-type" res-headers))) (parse res-body))) - (http-request-failed () - '(:|error| "API request failed"))))) + (http-request-failed (e) + (format *error-output* "microCMS status: ~D~%" (response-status e)))))) -(defun %build-uri (endpoint &optional (path "") (query nil)) +(defun %build-uri (endpoint &optional path query) (let ((uri (make-uri :scheme "https" :host (format nil "~A.microcms.io" *service-domain*) - :path (format nil "/api/v1/~A/~A" endpoint path) + :path (format nil "/api/v1/~A~@[/~A~]" endpoint path) :query (%build-query query)))) (render-uri uri)))