J@ArangoDB

{ "subject" : "ArangoDB", "tags": [ "multi-model", "nosql", "database" ] }

Handling Binary Data in Foxx 3.0

Note: this post is about the ArangoDB 3.x series

A while ago I wrote a blog post about handling binary data in Foxx applications. That blog post provided a solution for retrieving and serving non-UTF-8 data from a Foxx application. It was written for the 2.x series of ArangoDB.

With the release of ArangoDB 3.0 that solution needs some adaption, and this blog post provides the source code for the 3.0 version of the Foxx application.

The rawBodyBuffer() function of the request object is gone in 3.0, and to retrieve the body as a blob we now need to use req.rawBody. And as there are no controllers and applicationContexts in Foxx 3.0 anymore, the original route code needs to be changed from

2.8 Foxx action that can handle binary input
1
2
3
4
5
6
7
8
controller.post('/receive-binary', function (req, res) {
  // fetch request body into the buffer
  var body = req.rawBodyBuffer();
  // create an absolute filename, local to the Foxx application directory
  var filename = applicationContext.foxxFilename("body");

  require("fs").write(filename, body);
});

to the following code:

3.0 Foxx action that can handle binary input
1
2
3
4
5
6
7
8
router.post('/receive-binary', function (req, res) {
  // fetch request body into a Buffer
  var body = req.rawBody;
  // create an absolute filename, local to the Foxx application directory
  var filename = module.context.filename("body");

  require("fs").write(filename, body);
});

To serve binary data from a Foxx action, the original route code needs to be changed from

2.8 Foxx action that returns contents of a file
1
2
3
4
5
6
controller.get('/provide-binary-file', function (req, res) {
  // create an absolute filename, local to the Foxx application directory
  var filename = applicationContext.foxxFilename("body");
  // send the contents, this will also set mime type "application/octet-stream"
  res.sendFile(filename);
});
3.0 Foxx action that returns contents of a file
1
2
3
4
5
6
router.get('/provide-binary-file', function (req, res) {
  // create an absolute filename, local to the Foxx application directory
  var filename = module.context.fileName("body");
  // send the contents, this will also set mime type "application/octet-stream"
  res.sendFile(filename);
});

The adjusted Foxx application can be downloaded here with full source code.