REST API to analize CPF and return a pdf with the valid values
- DONE: Receive a CPF through the body of the API-request url.
- DONE: Validate the CPF, or discard the call.
- DONE: Cryptograph the CPF-string through a SHA256 transform.
- DONE: Insert the result in a PDF.
lein new app <my-application-name>
:dependencies [[org.clojure/clojure "1.10.0"]
;; Manage routers
[compojure "1.6.1"]
;; Create server
[http-kit "2.3.0"]
;; Standard ring response format
[ring/ring-defaults "0.3.2"]
;; Convert clojure maps into json format
[org.clojure/data.json "0.2.6"]
;; Generate pdf as response
[clj-pdf "2.5.8"]
;; Transform text into sha256
[digest "1.4.10"]
;; Validate cpf
[cadastro-de-pessoa "0.4.1"]]
Inspired by this post, which talks about a start point to writting APIs in Clojure.
So,
(defroutes app-routes
(GET "/cpf" [] cpf-handler)
(route/not-found "Error, page not found!"))
Will make us to request the page as
http://127.0.0.1:3000/cpf
This will make a call to cpf-handler.
These will transform our data.
;; ------ Helper functions --------
(defn crypto-cpf [cpf]
(digest/sha-256 (str cpf)))
;; (crypto-cpf "45350813870")
;; => "4146848f92fcd7aa18837a4fe7c72e4566514eaac4c8757637cfef82719650da"
;; Collection Helper functions to add a new cpf
;; Verify and encrypt, if the cpf is valid.
(defn crypto-if-valid [cpf]
(if (cpf/valid? cpf)
(str (crypto-cpf cpf))))
;; Write result to pdf.
(defn pdf-out [encrypted-cpf]
(pdf/pdf
[{}
[:phrase (str encrypted-cpf)]]
"doc.pdf"))
;; Composing the functions.
(defn pdf-crypted [cpf]
(pdf-out (crypto-if-valid (str cpf))))
;; test (valid cpf)
;; (pdf-crypted "15069602861")
;; Get the parameter specified by cpf, from :params object, in request.
(defn getparameter [req cpf] (get (:params req) cpf))
;; --------- Response ------------
;; Return "doc.pdf" at the root directory.
(defn cpf-handler [req]
{:status 200
:headers {"Content-Type" "text/json"}
:body
(->
(pdf-crypted (str (:cpf (:params req)))))})
;; (cpf-handler "http://127.0.0.1:3000/cpf?cpf=45350813870")
On the shell, in the ./applicantion/
root-path,
lein run
On the browser, after lein have loaded the project,
http://127.0.0.1:3000/cpf?cpf=45880813870
(this is a fake cpf and shouldn’t return anything.)
On the other hand, on the browser,
http://127.0.0.1:3000/cpf?cpf=45350813870
Should return a “doc.pdf” on the root of the application.
Example:
./application $ ls
doc src target test doc.pdf project.clj