dt0/models/Sessions.moon

38 lines
1.2 KiB
Plaintext
Raw Normal View History

2018-09-09 23:29:56 +00:00
import Model from require "lapis.db.model"
import Deltas from require "models"
import bytes from require "resty.random"
import to_hex from require "resty.string"
import abort from require "helpers"
class Sessions extends Model
@create: (input) =>
-- make sure a unique id is generated
2018-09-09 23:29:56 +00:00
id = input.id or to_hex bytes 16
while Sessions\find id: id
id = to_hex bytes 16
-- take user input time or when this request started processing
2018-09-09 23:29:56 +00:00
time = tonumber(input.started_at) or ngx.req.start_time!
values = {
started_at: time
updated_at: time
id: id
}
return super values
@update: (input) =>
-- user can manually change started_at and updated_at if they want
-- this will potentially invalidate data in the Deltas
2018-09-09 23:29:56 +00:00
values = {
started_at: tonumber(input.started_at) or nil
updated_at: tonumber(input.updated_at) or ngx.req.start_time!
}
local delta
if input.type
delta, err = Deltas\create session_id: @id, type: input.type, time: values.updated_at - @updated_at
unless delta
-- abort "Invalid type (must be <=255 bytes)."
abort "Failed to create delta: #{err}"
return super(values), delta