Skip to content

Instantly share code, notes, and snippets.

@josefrichter

josefrichter/pet.lfe

Created Sep 19, 2020
Embed
What would you like to do?
(defmodule nova-rest.controllers.pet
(export
(manage 1)))
(defun manage
;;
;; GET Handler (Index)
;;
([(map 'req (map 'method #"GET"))]
(let* (((tuple 'ok pets) (dets:open_file 'pets (tuple 'file "pets.dets")))
(pets (dets:match_object pets '$1))
(body (list-comp
((<- (tuple pet-id name) pets))
(map #"id" pet-id #"name" name))))
(tuple 'status 200 (map) (json:encode body (list 'maps 'binary)))))
;;
;; POST Handler (Create)
;;
([(map 'req (map 'method #"POST")
'json (map #"name" name))]
(let* (((tuple 'ok pets) (dets:open_file 'pets (tuple 'file "pets.dets")))
(pet-id (list_to_binary (uuid:uuid_to_string (uuid:get_v4))))
('ok (dets:insert pets (tuple pet-id name))))
(logger:debug "Pet ID: ~p" (list pet-id))
(tuple 'status 201 (map) (json:encode (map #"id" pet-id #"name" name) (list 'maps 'binary)))))
;;
;; GET Handler (Read)
;;
([(map 'req (map 'method #"GET" 'bindings (map 'petid pet-id)))]
(let (((tuple 'ok pets) (dets:open_file 'pets (tuple 'file "pets.dets"))))
(case (dets:lookup pets pet-id)
('()
(tuple 'status 404))
((list (tuple pet-id name))
(tuple 'status 200 (map) (json:encode (map #"id" pet-id #"name" name) (list 'maps 'binary)))))))
; (list 'maps 'binary) could be just '(maps binary)
;;
;; PUT Handler (Update)
;;
([(map 'req (map 'method #"PUT"
'bindings (map 'petid pet-id))
'json (map #"name" name))]
(let* (((tuple 'ok pets) (dets:open_file 'pets (tuple 'file "pets.dets")))
('ok (dets:delete pets pet-id))
('ok (dets:insert pets (tuple pet-id name))))
(tuple 'status 200 (map) (json:encode (map #"id" pet-id #"name" name) (list 'maps 'binary)))))
;;
;; DELETE Handler (Delete)
;;
([(map 'req (map 'method #"DELETE"
'bindings (map 'petid pet-id)))]
(let* (((tuple 'ok pets) (dets:open_file 'pets (tuple 'file "pets.dets")))
('ok (dets:delete pets pet-id)))
(tuple 'status 200)))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.