Skip to content

Instantly share code, notes, and snippets.

@thomasmichaelwallace
Created April 30, 2019 16:37
Show Gist options
  • Save thomasmichaelwallace/ba99a273dcde7389e1f9b0c8d68778c4 to your computer and use it in GitHub Desktop.
Save thomasmichaelwallace/ba99a273dcde7389e1f9b0c8d68778c4 to your computer and use it in GitHub Desktop.
squirreldex: the database module
// in node, a json file is just a module that exports a javascript object
// in this case, data.json is a map of squirrels keyed by id.
const data = require('./data.json');
const AdmZip = require('adm-zip') // node does not have native zip support
const AWS = require('aws-sdk');
const lambda = new AWS.lambda();
function get(id) {
// getting is very simple.
return data[id];
}
function getUpdatedZipBuffer(overrides) {
// to update a lambda function code, we need to provide the source
// as a buffer representation fo a zip file.
const zip = new AdmZip();
// lambda stores the function code in /var/task, so add the existing,
// unmodified source to start:
zip.addLocalFolder('/var/task');
Object.entries(overrides).forEach(([path, data]) => {
const buffer = Buffer.alloc(data.length, data);
zip.addFile(path, buffer); // add/replace source files as required
});
return zip.toBuffer();
}
function getUpdatedDataModuleSource(key, value) {
// the "data module" is a json file, which has already been parsed by the
// require at the start of the db module.
const updated = { ...data };
// therefore all we need to do is transform it...
if (value !== null) {
// replace squirrel by id if a new value is given
updated[key] = value;
} else {
// delete(?!) squirrel by id if not
delete updated[key];
}
// javascript provides a built-in way to go form JSON to source code:
return JSON.stringify(updated);
}
async function update(key, value) {
// first we transform the source code:
const newDataJson = getUpdatedDataModuleSource(key, value);
// then we build a deployment with the transformed source code:
const overrides = { './data.json', newDataJson };
const code = getUpdatedZipBuffer(overrides);
// and finally we re-deploy:
const params = { FunctionName: 'squirreldex', ZipFile: code }
return lambda.updateFunctionCode(params).promise();
}
module.exports = { get, update };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment