diff --git a/lib/vehicle.js b/lib/vehicle.js index 072e23f1..b585382b 100644 --- a/lib/vehicle.js +++ b/lib/vehicle.js @@ -5,6 +5,16 @@ const _ = require('lodash'); /** @exports Vehicle */ +/** + * @param {Object} response + * + * @return {Date|null} A parsed age or null if no age exists + */ +const parseAge = function(response) { + const age = _.get(response, 'headers.sc-data-age', null); + return age ? new Date(age) : null; +}; + /** * Initializes a new Vehicle to use for making requests to the Smartcar API. * @@ -138,7 +148,7 @@ Vehicle.prototype.location = function() { .then(function(response) { return { data: response.body, - age: new Date(response.headers['sc-data-age']), + age: parseAge(response), }; }); }; @@ -173,7 +183,7 @@ Vehicle.prototype.odometer = function() { .then(function(response) { return { data: response.body, - age: new Date(response.headers['sc-data-age']), + age: parseAge(response), unitSystem: response.headers['sc-unit-system'], }; }); diff --git a/test/lib/vehicle.js b/test/lib/vehicle.js index 1deed1cf..d4b35219 100644 --- a/test/lib/vehicle.js +++ b/test/lib/vehicle.js @@ -170,6 +170,23 @@ test('location', async function(t) { }); +test('location - no age', async function(t) { + + const body = { + latitude: 1234, + longitude: 1234, + }; + const headers = {}; + t.context.n = nocks.base() + .get('/location') + .reply(200, body, headers); + + const response = await vehicle.location(); + t.deepEqual(response.data, body); + t.is(response.age, null); + +}); + test('odometer', async function(t) { const body = { @@ -192,6 +209,25 @@ test('odometer', async function(t) { }); +test('odometer - no age', async function(t) { + + const body = { + distance: 1234, + }; + const headers = { + 'sc-unit-system': 'metric', + }; + t.context.n = nocks.base() + .get('/odometer') + .reply(200, body, headers); + + const response = await vehicle.odometer(); + t.deepEqual(response.data, body); + t.is(response.age, null); + t.is(response.unitSystem, headers['sc-unit-system']); + +}); + test('vin', async function(t) { const body = {