/*jshint node:true*/ 'use strict'; var db = require('../units/db-connector').dbConnection; var dbCompany = require('../units/db-company')(db); var dbAccounts = require('../units/db-accounts')(db); var $U = require('md-utils'); var events = require('events'); // Create an eventEmitter object var eventEmitter = new events.EventEmitter(); module.exports = function(app) { var express = require('express'); var newcompaniesRouter = express.Router(); eventEmitter.on('makeMemberOf', (uid, cid) => { console.log('Make ' + uid + ' a member of ' + cid); dbAccounts.makeMemberOf(uid, cid) .catch(function(err) { console.error(err); }); }); newcompaniesRouter.get('/', function(req, res) { res.send({ newcompanies: [] }); }); newcompaniesRouter.post('/', function(req, res) { var updateData = $U.unDashObject(req.body.data.attributes); if (/Bearer .+/.test(req.headers.authorization)) { dbCompany.addNewCompany(updateData) .then(function(d) { updateData.cid = d.cid; let response = { data: { type: 'newcompany', id: d.cid, attributes: updateData } }; eventEmitter.emit('makeMemberOf', updateData.uid, d.cid); res.status(200).send(response); }) .catch(function(e) { console.error(e); res.status(401).end(); }); } }); newcompaniesRouter.get('/:id', function(req, res) { res.send({ newcompanies: { id: req.params.id } }); }); newcompaniesRouter.put('/:id', function(req, res) { res.send({ newcompanies: { id: req.params.id } }); }); newcompaniesRouter.delete('/:id', function(req, res) { res.status(204).end(); }); // The POST and PUT call will not contain a request body // because the body-parser is not included by default. // To use req.body, run: // Npm install --save-dev body-parser app.use('/api/newcompanies', require('body-parser').json({type: 'application/vnd.api+json'})); // After installing, you need to `use` the body-parser for // this mock uncommenting the following line: app.use('/api/newcompanies', newcompaniesRouter); };