Using the Alma APIs with Node.js
In the past couple of years, Node.js has become quite popular. With its cross-platform support, powerful package manager, and asynchronous architecture, Node is the environment of choice for many greenfield applications today.
This simple example can get you started using the Alma APIs in a Node.js application. Since the Alma REST APIs return JSON natively and use accepted standards, it’s pretty straightforward to integrate them into your Node app. Let’s get started!
Stack
- Node.js which includes the runtime and the package manager
- Jade as the template engine for the views
- Express as the web framework
- And of course, Bootstrap for the front-end framework
Functionality
Scan-in Form
Controller and Alma.js Library
Once the form is built, we need to create a controller and begin to make our calls to the Alma API. For that, we add a new route in our app.js file to refer to the scan in controller:
var scanin = require('./routes/scan-in');
We create a scan-in.js file in the routes folder, and add a handler for the “get” action:
/* GET */ router.get('/', function(req, res, next) { getLibraries( function(err, data) { if (err) return next(err); res.render('scan-in/index', { title: 'Scan In Item', libraries: data }); } ); });
First, we add the relevant headers required for Alma APIs.
function performRequest(endpoint, method, data, callback) { var dataString = JSON.stringify(data); var headers = { 'Authorization': 'apikey ' + apikey, 'Accept': 'application/json' }; if (method != 'GET') { headers['Content-Type'] = 'application/json'; headers['Content-Length'] = dataString.length; }
Then we set the options required for the request:
var options = { uri: (endpoint.substring(0,4) == 'http' ? '' : host + path) + endpoint, method: method, headers: headers };
Finally, we call the request function provided by the Request Node package and handle the error or success response.
request( options, function(err, response, body) { if (!err && ('' + response.statusCode).match(/^[4-5]\d\d$/)) { console.log('Error from Alma: ' + body); var message; try { var obj = JSON.parse(body); message = obj.errorList.error[0].errorMessage + " (" + obj.errorList.error[0].errorCode + ")"; } catch (e) { message = "Unknown error from Alma."; } err = new Error(message); } if (err) callback(err); else callback(null, body); }); }
Posting the Scan-In Request
- Retrieves the library list in order to rebuild the form
- Retrieves the item record based on the barcode
- Sends a scan-in request to Alma and processes the result
- Returns the view with the information retrieved from Alma
Based on the callback model inherent to Node, we can handle errors which might return from Alma. In this example, Alma informed us that an invalid barcode was provided:
if (err) { if (err.message.indexOf("401690") > 0 || err.message.indexOf("401689") > 0) return res.render('scan-in/index', { title: 'Scan In Item', error: "Invalid barcode", libraries: libraries }); }