-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.lua
More file actions
109 lines (81 loc) · 2.39 KB
/
Copy pathapi.lua
File metadata and controls
109 lines (81 loc) · 2.39 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
if rawget(_ENV, 'mnr_sql') then
error(('mnr_sql api already loaded in %s - remove duplicate "@mnr_sql/api.lua" from fxmanifest.lua'):format(GetCurrentResourceName()))
end
local TIMEOUT = GetConvarInt('mnr_sql:api_timeout', 30000)
local resourceName = 'mnr_sql'
local ready = false
local pending = {}
local pendingCount = 0
local function waitReady()
if ready then return end
local co = coroutine.running()
if not co then
error('mnr_sql accessed outside a coroutine before it was ready', 2)
end
pendingCount = pendingCount + 1
pending[pendingCount] = co
local _, err = coroutine.yield()
if err then error(err, 2) end
end
local function resumeAll(err)
local snapshot = pending
local count = pendingCount
pending = {}
pendingCount = 0
for i = 1, count do
coroutine.resume(snapshot[i], nil, err)
end
end
local function markReady()
ready = true
resumeAll(nil)
end
local function awaitExport(exportName, query, params)
waitReady()
local awaitedPromise = promise.new()
exports[resourceName][exportName](nil, query, params, function(result)
awaitedPromise:resolve(result)
end)
local result = Citizen.Await(awaitedPromise)
return result.data, result.error
end
local function buildOperation(exportName)
return function(query, params)
return awaitExport(exportName, query, params)
end
end
---@class MnrSql
local mnr_sql = {}
mnr_sql.query = buildOperation('query')
mnr_sql.single = buildOperation('single')
mnr_sql.scalar = buildOperation('scalar')
mnr_sql.insert = buildOperation('insert')
mnr_sql.update = buildOperation('update')
mnr_sql.prepare = buildOperation('prepare')
mnr_sql.transaction = function(steps)
waitReady()
local awaitedPromise = promise.new()
exports[resourceName]:transaction(steps, function(result)
awaitedPromise:resolve(result)
end)
local result = Citizen.Await(awaitedPromise)
return result.data == true, result.error
end
mnr_sql.store = function(query)
return exports[resourceName]:store(query)
end
AddEventHandler('mnr_sql:ready', markReady)
CreateThread(function()
SetTimeout(TIMEOUT, function()
if ready then return end
resumeAll(('Timeout: %s did not become ready within %dms'):format(resourceName, TIMEOUT))
end)
if GetResourceState(resourceName) ~= 'started' then return end
local ok, alreadyReady = pcall(function()
return exports[resourceName]:isReady()
end)
if ok and alreadyReady then
markReady()
end
end)
rawset(_ENV, 'mnr_sql', mnr_sql)