Skip to content

Instantly share code, notes, and snippets.

@grantges
Last active April 26, 2016 21:41
Show Gist options
  • Save grantges/6b28922125ca4dd3feb41e6fea8438ab to your computer and use it in GitHub Desktop.
Save grantges/6b28922125ca4dd3feb41e6fea8438ab to your computer and use it in GitHub Desktop.

Response Format Block

NOTE: This is no longer required as of release 0.4.3, see the release notes @ http://docs.appcelerator.com/platform/latest/#!/guide/Arrow_Builder_0.4.3_Release_Note

This is a block that can be leveraged with Appcelerator Arrow MicroServices to allow consumers of the service to request the data be returned in a particular format based on a query string parameter. Typically this can be done using the Accept header value, but in some cases consumers may find it easier to leverage the query string.

var Arrow = require('arrow');
var TestAPI = Arrow.API.extend({
group: 'testapi',
path: '/api/testapi/:id',
method: 'GET',
description: 'this is an api that shows how to implement an API',
model: 'testuser',
before: 'responseFormatBlock', // <-- Here is how you would add this to the API
parameters: {
id: {description:'the test user id'},
format: {description: 'expected format', optional:true} // <-- add the `format` query parameter as optional
},
action: function (req, resp, next) {
resp.stream(req.model.find, req.params.id, next);
}
});
module.exports = TestAPI;
var Arrow = require('arrow');
var responseFormatBlock = Arrow.Block.extend({
name: 'responseFormatBlock',
description: 'Allows service consumer to request data in a particular format through the query string vs Accept header.',
action: function (req, resp) {
if(req.query && req.query.format){
switch(req.query.format){
case 'xml':
req.headers.accept = 'application/xml';
break;
case 'txt':
req.headers.accept = 'text/plain';
break;
case 'csv':
req.headers.accept = 'text/csv';
break;
case 'yaml':
req.headers.accept = 'application/yaml';
break;
default:
req.headers.accept = 'application/json';
}
}
}
});
module.exports = responseFormatBlock;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment