46 lines
1.0 KiB
Plaintext
46 lines
1.0 KiB
Plaintext
lapis = require "lapis"
|
|
|
|
import Sessions, Deltas from require "models"
|
|
import api, abort from require "helpers"
|
|
|
|
get = (id="") ->
|
|
if session = Sessions\find(:id) or Sessions\create(:id)
|
|
return session, Deltas\select "WHERE session_id = ?", session.id
|
|
else
|
|
abort "Invalid session ID."
|
|
|
|
types = (deltas) ->
|
|
tab = {}
|
|
for delta in *deltas
|
|
tab[delta.type] = delta.time
|
|
return tab if #tab > 0
|
|
|
|
result = (session, deltas) ->
|
|
{
|
|
id: session.id, time: session.updated_at - session.started_at,
|
|
types: types deltas
|
|
}
|
|
|
|
update = =>
|
|
session, deltas = get(@params.id)
|
|
session, delta = session\update(@params)
|
|
table.insert deltas, delta if delta
|
|
return result session, deltas
|
|
|
|
delete = =>
|
|
session = get(@params.id)
|
|
ok, err = session\delete!
|
|
abort err unless ok
|
|
return deleted: true
|
|
|
|
fns = {
|
|
GET: => result get(@params.id)
|
|
POST: => update(@)
|
|
PUT: => update(@)
|
|
DELETE: => delete(@)
|
|
}
|
|
|
|
class extends lapis.Application
|
|
[session: "/0/:id[a-fA-F%d]"]: api fns
|
|
[new_session: "/0/new"]: api fns
|