Created
June 8, 2012 15:50
-
-
Save mikekatz/2896309 to your computer and use it in GitHub Desktop.
Save Lua Table to Kinvey - blog example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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