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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83 import tables, random, os, times, json, asyncfile, asyncdispatch
import types, cache_types, utils
import nimhafas
randomize()
proc cacheExists* (id: string ): bool =
return fileExists(getEnv("CACHE_PATH") & "/" & $id & ".json")
proc getFreeId (): string =
result = toAlphaId(int32(rand(high(int32))))
while fileExists(getEnv("CACHE_PATH") & "/" & $result & ".json"):
result = toAlphaId(int32(rand(high(int32))))
proc getCacheObject* (reqId: string): CacheObject =
if not cacheExists(reqId): raise newException(notFoundException, "REQUEST_NOT_FOUND")
return parseFile(getEnv("CACHE_PATH") & "/" & $reqId & ".json").to(CacheObject)
proc saveJourneys* (params: JourneysParams, journeysResponse: JourneysResponse): Future[CacheObject] {.async.} =
let reqId = getFreeId()
let lastUpdated = getTime().toUnix()
var journeys = initTable[string, Journey]()
var maxId = -1
for journey in journeysResponse.journeys:
inc(maxId)
journeys[$maxId] = journey
var cacheObj = CacheObject(
version: 1,
reqId: reqId,
minId: 0,
maxId: maxId,
earlierRef: journeysResponse.earlierRef,
laterRef: journeysResponse.laterRef,
lastUpdated: lastUpdated,
params: params,
journeys: journeys
)
var file = openAsync(getEnv("CACHE_PATH") & "/" & $reqId & ".json", fmReadWrite)
await file.write($(%* cacheObj))
return cacheObj
proc updateJourneys* (reqId: string, mode: moreJourneysMode, journeysResponse: JourneysResponse): Future[CacheObject] {.async.} =
var cacheObj = getCacheObject(reqId)
if mode == earlier:
cacheObj.minId -= journeysResponse.journeys.len
var cnt = cacheObj.minId
for journey in journeysResponse.journeys:
cacheObj.journeys[$cnt] = journey
inc(cnt)
else:
for journey in journeysResponse.journeys:
inc(cacheObj.maxId)
cacheObj.journeys[$cacheObj.maxId] = journey
cacheObj.lastUpdated = getTime().toUnix()
if mode != later:
cacheObj.earlierRef = journeysResponse.earlierRef
else:
cacheObj.laterRef = journeysResponse.laterRef
var file = openAsync(getEnv("CACHE_PATH") & "/" & $reqId & ".json", fmReadWrite)
await file.write($(%* cacheObj))
return cacheObj
proc updateJourney* (reqId: string, journeyId: string, journey: Journey): Future[CacheObject] {.async.} =
var cacheObj = getCacheObject(reqId)
cacheObj.lastUpdated = getTime().toUnix()
cacheObj.journeys[journeyId] = journey
var file = openAsync(getEnv("CACHE_PATH") & "/" & $reqId & ".json", fmReadWrite)
await file.write($(%* cacheObj))
return cacheObj