-
Notifications
You must be signed in to change notification settings - Fork 1
/
name.cr
46 lines (39 loc) · 1.16 KB
/
name.cr
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
34
35
36
37
38
39
40
41
42
43
44
45
46
module CrystalDemo
module NameApp
extend CrystalDemo::MessageUtils
get "/names" do |env|
page = env.params.query.fetch("page", "1").to_i - 1
query = Crecto::Repo::Query
.limit(10)
.offset(page * 10)
.order_by("id desc")
names = Repo.all(Name, query)
(names.as(Array).map &.to_hash).to_json
end
post "/names" do |env|
name = Name.from_json(env.params.json.to_json)
changeset = CrystalDemo::Name.changeset(name)
if changeset.valid?
name = CrystalDemo::Repo.insert(changeset)
name.instance.to_json
else
halt env, status_code: 406, response: invalid(changeset)
end
end
put "/names/:id" do |env|
name = Repo.get(Name, env.params.url["id"])
if name
name.from_json(env.params.json.to_json)
changeset = CrystalDemo::Name.changeset(name)
if changeset.valid?
name = CrystalDemo::Repo.update(name)
name.instance.to_json
else
halt env, status_code: 406, response: invalid(changeset)
end
else
halt env, status_code: 404, response: not_found
end
end
end
end