summaryrefslogtreecommitdiff
path: root/extra/http/client.lisp
blob: a694612e6998aba5a6a8dc7311a163d31edbac69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
(in-package #:eris-http-client)

(defclass http-backend (eris:encoding-backend eris:decoding-backend)
  ((endpoint :initarg :endpoint :type quri:uri
             :documentation "HTTP endpoint to use.")
   (auth :initarg :auth :type cons
         :documentation "A login:password pair for HTTP Basic auth.")))

(defmethod initialize-instance ((http-backend http-backend) &rest initargs
                                &key (endpoint nil endpoint-p)
                                  (auth nil)
                                &allow-other-keys)
  (declare (ignore initargs))
  (unless endpoint-p
    (error 'simple-error "An endpoint must be specified."))
  (let ((uri (quri:uri endpoint)))
    ;; To prevent confusion of what part of the endpoint should be included
    (unless (string-suffix-p "/uri-res/" (quri:uri-path uri))
      (error 'simple-error "Endpoint must end in /uri-res/."))
    (with-slots (eris:output-function eris:fetch-function) http-backend
      (setf (quri:uri-path uri) (concatenate 'string (quri:uri-path uri) "N2R"))
      (setf eris:fetch-function
            (lambda (reference)
              (setf (quri:uri-query uri) (eris:reference-to-block-urn reference))
              (mvlet ((body status (dexador:get uri)))
                (if (eql status 404)
                    (error 'eris:missing-block)
                    body)))
            eris:output-function
            (lambda (block reference)
              (setf (quri:uri-query uri) (eris:reference-to-block-urn reference))
              (dexador:post uri :force-binary t :content block :basic-auth auth)
              block)))))