Add json api handler

This commit is contained in:
Akira Tempaku 2025-05-17 16:37:45 +09:00
parent f9dbc124b3
commit d508d9ec70
Signed by: paku
GPG key ID: 5B4E8402BCC50607
5 changed files with 46 additions and 20 deletions

1
qlfile
View file

@ -9,3 +9,4 @@ ql clack-errors
git microcms https://github.com/skyizwhite/microcms-lisp-sdk
ql local-time
ql function-cache
ql jonathan

View file

@ -46,3 +46,7 @@
(:class qlot/source/ql:source-ql
:initargs (:%version :latest)
:version "ql-2023-10-21"))
("jonathan" .
(:class qlot/source/ql:source-ql
:initargs (:%version :latest)
:version "ql-2020-09-25"))

12
src/helper.lisp Normal file
View file

@ -0,0 +1,12 @@
(defpackage #:website/helper
(:use #:cl
#:jingle)
(:export #:api-p))
(in-package #:website/helper)
(defun starts-with-p (prefix string)
(let ((pos (search prefix string :start1 0 :end1 (length prefix) :start2 0)))
(and pos (= pos 0))))
(defun api-p ()
(starts-with-p "/api/" (request-uri *request*)))

View file

@ -1,7 +1,9 @@
(defpackage #:website/renderer
(:use #:cl
#:hsx
#:jingle)
#:jingle
#:website/helper
#:jonathan)
(:import-from #:hsx/element
#:element)
(:import-from #:website/components/metadata
@ -13,17 +15,21 @@
(in-package #:website/renderer)
(defmethod jingle:process-response :around ((app jingle:app) result)
(set-response-header :content-type "text/html; charset=utf-8")
(when (eq (request-method *request*) :get)
(set-response-header :cache-control "public, max-age=60"))
(call-next-method app
(render-to-string
(hsx (html :lang "ja"
(head
(~metadata :metadata (context :metadata))
(~scripts))
(body
:hx-ext "head-support, response-targets, preload"
:hx-boost "true" :hx-swap "transition:true"
:hx-target-404 "body" :hx-target-5* "body"
(~layout result)))))))
(cond ((api-p)
(set-response-header :content-type "application/json; charset=utf-8")
(call-next-method app (to-json result)))
(t
(set-response-header :content-type "text/html; charset=utf-8")
(call-next-method app
(render-to-string
(hsx (html :lang "ja"
(head
(~metadata :metadata (context :metadata))
(~scripts))
(body
:hx-ext "head-support, response-targets, preload"
:hx-boost "true" :hx-swap "transition:true"
:hx-target-404 "body" :hx-target-5* "body"
(~layout result)))))))))

View file

@ -1,7 +1,8 @@
(defpackage #:website/routes/not-found
(:use #:cl
#:hsx
#:jingle)
#:jingle
#:website/helper)
(:export #:handle-not-found))
(in-package #:website/routes/not-found)
@ -12,9 +13,11 @@
(defun handle-not-found ()
(setf (context :metadata) *metadata*)
(hsx
(div :class "flex flex-col h-full items-center justify-center gap-y-6"
(h1 :class "font-bold text-2xl"
"404 Not Found")
(a :href "/" :class "text-lg text-pink-500 hover:underline"
"Back to TOP"))))
(if (api-p)
'(:|message| "404 Not Found")
(hsx
(div :class "flex flex-col h-full items-center justify-center gap-y-6"
(h1 :class "font-bold text-2xl"
"404 Not Found")
(a :href "/" :class "text-lg text-pink-500 hover:underline"
"Back to TOP")))))