Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ring Middleware の基礎

ayato
June 26, 2016

Ring Middleware の基礎

ayato

June 26, 2016
Tweet

More Decks by ayato

Other Decks in Programming

Transcript

  1. 3JOH.JEEMFXBSF (defn wrap-member [handler] (fn [req] (->> (get-in req [:params

    :member-id]) find-member (assoc req :member) handler))) ߴ֊ؔ਺ ϋϯυϥΛड͚औΔ ϦΫΤετΛऔΔؔ਺Λฦ͢ ৽͍͠ϋϯυϥ
  2. (defn wrap-member [handler] (fn [req] (->> (get-in req [:params :member-id])

    find-member (assoc req :member) handler))) 3JOH.JEEMFXBSF ߴ֊ؔ਺ ϋϯυϥΛड͚औΔ ϦΫΤετΛऔΔؔ਺Λฦ͢ ৽͍͠ϋϯυϥ ϋϯυϥ ϦΫΤετ ؔ਺
  3. .JEEMFXBSFΛద༻͢Δ (defn wrap-answer [handler] (fn [req] (handler (assoc req :ans

    42)))) (defn handler [req] (res/response (get req :ans))) XSBQBOTXFSϛυϧ΢ΣΞΛIBOEMFS΁ద༻͢Δ (def app (wrap-answer handler))
  4. .JEEMFXBSFΛద༻͢Δ (let [handler (fn [req] (res/response (get req :ans))] (fn

    [req] (handler (assoc req :ans 42)))) XSBQBOTXFSϛυϧ΢ΣΞΛIBOEMFS΁ద༻͢Δ (fn [req] (res/response (get (assoc req :ans 42) :ans)))
  5. ϦΫΤετͷྲྀΕ Handler Middleware A Middleware B Middleware C Request Response

    .JEEMFXBSF$͕ϦΫΤετϚοϓΛॲཧ͠ ৽ͨͳϦΫΤετϚοϓΛ࣍ͷϋϯυϥ΁౉͢
  6. ϦΫΤετͷྲྀΕ Handler Middleware A Middleware B Middleware C Request Response

    .JEEMFXBSF#͕ϦΫΤετϚοϓΛॲཧ͠ ৽ͨͳϦΫΤετϚοϓΛ࣍ͷϋϯυϥ΁౉͢
  7. ϦΫΤετͷྲྀΕ Handler Middleware A Middleware B Middleware C Request Response

    .JEEMFXBSF"͕ϦΫΤετϚοϓΛॲཧ͠ ৽ͨͳϦΫΤετϚοϓΛ࣍ͷϋϯυϥ΁౉͢
  8. ϦΫΤετͷྲྀΕ Handler Middleware A Middleware B Middleware C Request Response

    )BOEMFS͕ϦΫΤετϚοϓΛॲཧ͠ ϨεϙϯεϚοϓΛੜ੒ฦ٫͢Δ
  9. ϦΫΤετͷྲྀΕ Handler Middleware A Middleware B Middleware C Request Response

    .JEEMFXBSF"͕ϨεϙϯεϚοϓΛॲཧ͠ ৽ͨͳϨεϙϯεϚοϓΛฦ٫͢Δ
  10. ϦΫΤετͷྲྀΕ Handler Middleware A Middleware B Middleware C Request Response

    .JEEMFXBSF#͕ϨεϙϯεϚοϓΛॲཧ͠ ৽ͨͳϨεϙϯεϚοϓΛฦ٫͢Δ
  11. ϦΫΤετͷྲྀΕ Handler Middleware A Middleware B Middleware C Request Response

    .JEEMFXBSF$͕ϨεϙϯεϚοϓΛॲཧ͠ ৽ͨͳϨεϙϯεϚοϓΛฦ٫͢Δ
  12. ϦΫΤετϚοϓߋ৽ύλʔϯ (defn wrap-member [handler] (fn [req] (->> (get-in req [:params

    :member-id]) find-member (assoc req :member) handler))) ϦΫΤετϚοϓΛߋ৽ͯ͠ϋϯυϥ΁౉͢ Ұൠతʹϋϯυϥ΁౉͢લͷڞ௨ॲཧΛ୲͏ ϦΫΤετϚοϓʹ௥Ճ
  13. (defn wrap-html [handler] (fn [req] (-> (handler req) (res/content-type "text/html"))))

    ϨεϙϯεϚοϓߋ৽ύλʔϯ ϋϯυϥͷฦ٫ͨ͠ϨεϙϯεϚοϓΛߋ৽͢Δ Ϩεϙϯεͷ.*.&λΠϓΛ
 ౷Ұͨ͠Γ͢Δͷʹศར ϨεϙϯεϚοϓʹ௥Ճ
  14. (defn wrap-auth [handler] (fn [req] (if (authenticated? req) (handler req)

    (auth-error-handler req)))) ৚݅෼ذύλʔϯ ࣮ߦ͢ΔϋϯυϥΛ৚݅ʹΑͬͯมߋ͢Δ ϧʔςΟϯά΍ೝূೝՄͷॲཧΛ͢Δ
 ڞ௨ॲཧͰར༻͞ΕΔ ৚݅Ͱ࣮ߦର৅Λมߋ
  15. (defn wrap-fib [handler] (let [memoized-fib (memoize fib)] (fn [req] (let

    [n (->long (get-in req [:params :n]))] (-> (assoc req :fib-num (memoized-fib n)) handler))))) Ϋϩʔδϟ ดแ ύλʔϯ ؀ڥΛด͡ࠐΊͯ৽͍͠ϋϯυϥΛฦ٫͢Δ ॏ͍ॲཧͳͲΛϝϞԽͨ͠ΓɺԿ౓΋ܭࢉ͢Δҙຯ ͕ͳ͍΋ͷΛด͡ࠐΊͯ͠·͑Δ ฦ٫͢Δؔ਺ʹด͡ࠐΊΔ
  16. ໰୊ (defn show-user [req] (let [user-id (get-in req [:params :user-id])

    db (:db req) (-> (find-user-by-id db user-id) res/ok
 res/html)))