var pg, log; function init(config) { pg = config.pg; log = config.log; } exports.init = init; var deviceR = /^\/diller\/([0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5})\//; function onMessage(topic, message, payload) { var matches = deviceR.exec(topic) if (!matches) { log.warn('no match: ', topic); return; } var mac = matches[1]; pg.connect(function (err, client, done) { if (err) { done(); log.error('Could not connect to postgres', err); return; } client.query('select count(*) as count from device where key=$1', [mac], function (err, result) { if (err) { done(); log.error('error running query', err); return; } if (result.rows[0].count > 0) { done(); return; } log.info('New device:', mac); client.query('insert into device(id, key, created_timestamp) values(default, $1, current_timestamp) returning id', [mac], function (err, result) { if (err) { done(); log.error('error inserting new device', err); } log.info('New device created', result.rows[0].id); done(); }); }); }); } exports.onMessage = onMessage;