Last active
August 15, 2016 22:57
-
-
Save TheConnMan/796c74326ab26facd12fee06172751c8 to your computer and use it in GitHub Desktop.
Bonsai Water Post
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
app.get('/api/:fn', function(req, res) { | |
try { | |
var result = { | |
"ok": true | |
}; | |
if (req.query.apiKey !== process.env.API_KEY) { | |
throw "Invalid API key"; | |
} | |
if (!req.query.clientId || req.query.clientId.length === 0) { | |
throw "A client ID is required"; | |
} | |
if (req.params.fn == "put") { | |
if (!req.query.payload || req.query.payload.length === 0) { | |
throw "A payload is required"; | |
} | |
try { | |
JSON.parse(req.query.payload); | |
} catch (e) { | |
throw "Payload is not JSON"; | |
} | |
result.success = true; | |
storage.put(req.query.clientId, req.query.payload); | |
} | |
if (req.params.fn == "get") { | |
result.success = true; | |
var payload = storage.get(req.query.clientId); | |
if (payload) { | |
result.success = true; | |
result.message = JSON.parse(payload); | |
} else { | |
result.success = false; | |
} | |
} | |
res.json(result); | |
} catch (e) { | |
console.log(e); | |
res.json({ | |
"ok": false, | |
"error": e | |
}); | |
} | |
}); |
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
module.exports = { | |
put: function(client, payload) { | |
var clientPath = path + '/' + client + '/'; | |
if (!fs.existsSync(clientPath)) { | |
fs.mkdirSync(clientPath); | |
} | |
fs.writeFileSync(clientPath + new Date().getTime(), payload); | |
}, | |
get: function(client) { | |
var clientPath = path + '/' + client + '/'; | |
if (!fs.existsSync(clientPath)) { | |
return false; | |
} | |
var files = fs.readdirSync(clientPath).sort(); | |
if (files.length === 0) { | |
return false; | |
} | |
var contents = fs.readFileSync(clientPath + files[0]); | |
fs.unlinkSync(clientPath + files[0]); | |
if (files.length === 1) { | |
fs.rmdirSync(clientPath); | |
} | |
return contents; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment