Microservice Recipe: Batch Inserts

Service Recipes > Batch Inserts
19 Jun 2016

Submit and persist multiple JSON objects within a single POST request.

Collecting single event items is typical however, many use cases require batch loading of data. The submission of multiple events or records within a single request is both useful and efficient.

ExamplePOSTFunction

Consider the below function. This preforms a single store insert for multiple data items:

function onPost(context) {

return context.stores.default().table() .insert(request.payload.records.map(record => ({ data: JSON.stringify(record.data) }))); } module.exports = onPost;

Using native ES6mapfunctionality, it is simple to iterate through the inboundrecordsarray and process each data item. This means this function can support single key/values such as:

{
    "records": [
        {
            "data": 56
        },
        {
            "data": 234
        }
    ]
}

as well as more complex objects as follows:

{
  "records": [
    {
      "data": {
        "session_id": "p376dm2t",
        "msg": "foo"
      }
    },
    {
      "data": {
        "session_id": "y286zu2q",
        "msg": "bar"
      }
    }
  ]
}

Get Started For Free

Get Started