Skip to content
This repository has been archived by the owner on Jan 15, 2021. It is now read-only.

Docker development environment #51

Merged
merged 12 commits into from
May 22, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,16 @@
"name": "Launch Sticker App Gateway",
"program": "${workspaceRoot}/apigateway/app.js"
},
{
"type": "node",
"request": "attach",
"name": "Attach (apigateway)",
"address": "localhost",
"port": 5859,
"localRoot": "${workspaceRoot}/apigateway",
"remoteRoot": "/app/",
"restart": true
},
{
"type": "node",
"request": "attach",
Expand Down
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
**Setup and launch:**

```bash
npm install
npm run build
npm start
docker-compose -f docker-compose.dev.yml up -d
```

Then open your browser to [http://localhost:3000](http://localhost:3000)
9 changes: 0 additions & 9 deletions apigateway/Dockerfile

This file was deleted.

5 changes: 5 additions & 0 deletions apigateway/Dockerfile.dev
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
FROM node:7.9.0-alpine
RUN npm install -g nodemon
WORKDIR /app
ADD package.json .
RUN npm install
21 changes: 13 additions & 8 deletions apigateway/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,24 @@ var path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const passport = require('passport');
const proxy = require('http-proxy-middleware');
const authService = require('./services/auth');
const serverConnection = require('./config/database-config').serverConnection;

const users = require('./routes/users');
const browse = require('./routes/browse');
const cart = require('./routes/cart');
const feedback = require('./routes/feedback');
const create = require('./routes/create');
const checkout = require('./routes/checkout');
const trending = require('./routes/trending');
const history = require('./routes/history');

const app = express();

//TODO: Need to update this to correct path; need to take into account docker as well here
const PROJECT_ROOT = path.join(__dirname, '..');
app.use(express.static(path.resolve(__dirname, 'client', 'dist')));
app.set('views', path.resolve(__dirname, 'templates'));
app.set('etag', false);
app.set('views', path.join(PROJECT_ROOT, 'apigateway', 'templates'));
app.set('view engine', 'pug');
app.use(express.static(path.join(PROJECT_ROOT, 'client', 'dist')));

require('./strategy/aad-b2c')();
require('./strategy/passport')();
Expand All @@ -48,6 +48,11 @@ app.use('/users', users);
app.use('/browse', browse);
app.use('/cart', cart); //TODO: Will require auth
app.use('/create', create); //TODO: Will require auth
app.use('/history', history);
app.use('/trending', trending);

// proxy socket communication to the sticker service
app.use('/socket.io', proxy(process.env.STICKER_SERVICE_URL, { ws: true }));

app.get('/', function stickerRootRedirection(req, res) {
console.log('app.js: redirecting to browse');
Expand All @@ -60,8 +65,8 @@ app.use(authService.verifyUserLoggedIn);
app.use('/checkout', checkout);
app.use('/feedback', feedback);

const server = app.listen(serverConnection.port, () => {
console.log(`Sticker server running on port ${server.address().port}`);
const server = app.listen(process.env.PORT, () => {
console.log(`apigateway listening on port ${server.address().port}`);
});

module.exports = app;
module.exports = app;
9 changes: 0 additions & 9 deletions apigateway/config/database-config.js

This file was deleted.

6 changes: 0 additions & 6 deletions apigateway/config/services-config.js

This file was deleted.

6 changes: 6 additions & 0 deletions apigateway/debug.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
CHECKOUT_SERVICE_URL=http://checkout:5000
DB_URL=mysql://root@authdb/StickerDemoApp
NODE_ENV=development
PORT=3000
SESSION_SERVICE_URL=http://session:4000
STICKER_SERVICE_URL=http://stickers:2000
1 change: 1 addition & 0 deletions apigateway/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"express": "~4.14.1",
"express-session": "^1.15.2",
"guid": "0.0.12",
"http-proxy-middleware": "^0.17.4",
"morgan": "~1.7.0",
"mysql": "^2.13.0",
"passport": "^0.3.2",
Expand Down
31 changes: 10 additions & 21 deletions apigateway/routes/browse.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
'use strict';

//TODO: This functionality is temporary until integated with the new cart microservice; note that this currently calls into the "dummy" data access layer
const express = require('express');
const bodyParser = require('body-parser');
const router = express.Router();
const request = require('request');
const router = require('express').Router();

const dataAccess = require('../temp/db/data-access');

router.use(bodyParser.json());
const URL = `${process.env.STICKER_SERVICE_URL}/stickers`;

router.get('/', function stickerRouteBrowse(req, res) {
const renderData = { pageTitle: 'Browse', entry: 'browse' };
Expand All @@ -18,21 +14,14 @@ router.get('/', function stickerRouteBrowse(req, res) {
});

router.get('/api/items', function stickerRouteApiBrowse(req, res) {
// Do things with req.query.tags
let tags;
if (req.query.tags) {
tags = req.query.tags.split(',');
}

dataAccess.getStickers(tags, (items) => {
console.info('%d stickers found', items.length);
if (tags) {
console.log('Tags used in filter: ', tags);
const options = { url: URL, qs: { tags: req.query.tags }, json: true };
request.get(options, (error, response) => {
if (error) {
console.error(error);
res.sendStatus(500);
} else {
res.send({ items: response.body });
}

res.send({
items
});
});
});

Expand Down
95 changes: 52 additions & 43 deletions apigateway/routes/cart.js
Original file line number Diff line number Diff line change
@@ -1,64 +1,73 @@
'use strict';

//TODO: This functionality is temporary until integated with the new cart microservice; note that this currently calls into the "dummy" data access layer
const express = require('express');
const bodyParser = require('body-parser');
const dataAccess = require('../temp/db/data-access');
const express = require('express');
const request = require('request');

const CART_URL = `${process.env.SESSION_SERVICE_URL}/cart`;
const router = express.Router();
router.use(bodyParser.json());

router.get('/', function stickerRouteCart(req, res) {
res.render('index', { pageTitle: 'Cart', entry: 'cart' });
});

function sendItems(token, res) {
dataAccess.getCart(token, (items) => {
dataAccess.getStickers(null, (stickers) => {
res.send({
items: items.map((id) => stickers.filter((sticker) => sticker.id.toString() === id)[0])
});
});
});
}

router.get('/api/items', (req, res) => {
if (!req.query.token) {
res.status(401).send('Unauthorized');
return;
}
sendItems(req.query.token, res);
});
router.use(bodyParser.json());

router.put('/api/items/:item_id', (req, res) => {
if (!req.body.token) {
res.status(401).send('Unauthorized');
return;
// TODO this enables carts for unauthenticated users, passing the uuid
// generated by the client to the session service as the user's id.
// Moving the user's unauthenticated cart to one stored with their
// permanent id upon login is unimplemented.
router.use((req, res, next) => {
// the client passes the uuid in the query string for GET
// requests, in body JSON for PUT
if (!req.user) {
req.user = { id: req.query.token || req.body.token };
}

console.log('Item targetted %s', req.params.item_id);
next();
});

dataAccess.addToCart(req.body.token, req.params.item_id, () => {
dataAccess.getSticker(req.params.item_id, (item) => {
if (!item) {
dataAccess.addStickers([ req.body.item ], () => sendItems(req.body.token, res));
} else {
sendItems(req.body.token, res);
}
});
router.get('/api/items', function getCart(req, res) {
request.get(CART_URL, {
headers: { stickerUserId: req.user.id },
json: true
}, (error, response) => {
if (error) {
console.error(error);
res.sendStatus(500);
} else {
res.send(response.body);
}
});
});

router.delete('/api/items/:item_id', (req, res) => {
if (!req.body.token) {
res.status(401).send('Unauthorized');
return;
}

console.log('Item targetted', req.params.item_id);
router.delete('/api/items/:item_id', function removeItem(req, res) {
console.log('Item targeted', req.params.item_id);
request.delete(`${CART_URL}/${req.params.item_id}`, {
headers: { stickerUserId: req.user.id },
json: true
}, (error, response) => {
if (error) {
console.error(error);
res.sendStatus(500);
} else {
res.send(response.body);
}
});
});

dataAccess.removeFromCart(req.body.token, req.params.item_id, () => {
sendItems(req.body.token, res);
router.put('/api/items/:item_id', function addItem(req, res) {
request.put(`${CART_URL}/${req.params.item_id}`, {
headers: { stickerUserId: req.user.id },
body: req.body,
json: true
}, (error, response) => {
if (error) {
console.error(error);
res.sendStatus(500);
} else {
res.send(response.body);
}
});
});

Expand Down
40 changes: 20 additions & 20 deletions apigateway/routes/checkout.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@

'use strict';

//TODO: This is temporary using the "dummy" data access layer in order to interact with the cart; this will be removed when integrated with new cart microservice
const dataAccess = require('../temp/db/data-access');

const express = require('express');
const request = require('request');
const guid = require('guid');

//This route calls into the ASP.NET Core checkout microservice
const checkoutServiceUrl = require('../config/services-config').checkoutServiceUrl; //TODO: add env url lookup
const checkoutServiceUrl = process.env.CHECKOUT_SERVICE_URL;

const router = express.Router();
const bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));

router.post('/', function stickerRouteCheckout(req, res) {

var orderJson = {
Id: guid.raw(),
FullName : req.body['checkout-name'],
Email : req.body['checkout-email'],
Items : req.body['checkout-items']
FullName: req.body['checkout-name'],
Email: req.body['checkout-email'],
Items: req.body['checkout-items']
};

request({
Expand All @@ -32,19 +27,24 @@ router.post('/', function stickerRouteCheckout(req, res) {
headers: {
//Pass the current authenticated user's id to the checkout microservice
'stickerUserId': req.user.id
}},
function finishAddOrder(error){
if (error) {
console.log('Adding Order failed: ' + error);
} else {
console.log('Order added');
}

//TODO: Need to update this when the new cart microservice is integrated; for now, calls into the "dummy" data access layer
dataAccess.clearCart(req.body.token, () => {
}
}, function finishAddOrder(error) {
if (error) {
console.log('Adding Order failed: ' + error);
res.sendStatus(500);
} else {
console.log('Order added');
request.delete({
url: `${process.env.SESSION_SERVICE_URL}/cart`,
headers: { 'stickerUserId': req.user.id }
}, (error, response) => {
if (error) {
console.error(error);
}
res.render('index', { pageTitle: 'Checkout', entry: 'checkout' });
});
});
}
});
});

module.exports = router;
Loading