Skip to content

Instantly share code, notes, and snippets.

@jjfajardo
Forked from mikekatz/SaveLuaTableToKinvey.lua
Last active August 29, 2015 14:23
Show Gist options
  • Save jjfajardo/33f00a27ae5f344d232a to your computer and use it in GitHub Desktop.
Save jjfajardo/33f00a27ae5f344d232a to your computer and use it in GitHub Desktop.
-- load required modules
http = require("socket.http") --luasocket
ltn12 = require("ltn12")
mime = require("mime")
io = require("io")
json = require("json") -- luajson
-- Create a Lua table to represent our entity to save
--- This is from our doc REST example: http://docs.kinvey.com/rest-appdata.html
jamesBond = { ["firstName"] = "James", ["lastName"] = "Bond", ["email"] = "[email protected]", ["age"] = 34 }
-- Save the table to the backend
--- convert to json
jsstr = json.encode(jamesBond)
source = ltn12.source.string(jsstr); -- need to use a ltn12 source to supply the body
--- build a http request
response = {}
save = ltn12.sink.table(response) -- need a l1tn12 sink to get back the page content
jsonsize = # jsstr -- get the content size, needed for the header
-- build the headers. mime.b64 base64-encodes our credentials needed to communicate with this kinvey App
h = {Authorization = "Basic " .. (mime.b64("KIVEY_APP_ID:KINVEY_APP_SECRET")), ["Content-Type"] = "application/json", ["content-length"] = jsonsize }
--- send the request
ok, code, headers = http.request{url = "https://baas.kinvey.com/appdata/KINVEY_APP_ID/testObjects", redirect = true, method = "POST", headers = h, source = source, sink = save}
--- show that we got a valid response
print(code) -- should be 201 for POST success
saveditem = response[1]; -- kinvey appdata responses return arrays (which are tables in Lua)
print(saveditem)
--- convert from json to lua object
objAsTable = json.decode(saveditem)
for k,v in pairs(objAsTable) do print(k,v) end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment