Skip to content

Commit

Permalink
refactor db import
Browse files Browse the repository at this point in the history
  • Loading branch information
haipham23 committed Sep 29, 2017
1 parent 75c400c commit 5009975
Show file tree
Hide file tree
Showing 11 changed files with 120 additions and 83 deletions.
4 changes: 3 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"setTimeout": true,
"process": true,
"require": true,
"module": true
"module": true,
"after": true,
"before": true
}
}
34 changes: 17 additions & 17 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 4 additions & 6 deletions src/controllers/accountController.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@ const {
* create account
* @param {object} req request object
* @param {object} res response object
* @param {object} db database object
*/
function create(req, res, db) {
function create(req, res) {
accountServices
.create(req.body, db)
.create(req.body)
.then((result) => res.json(result))
.catch((error) => res.status(400).json(error.message));
}
Expand All @@ -21,11 +20,10 @@ function create(req, res, db) {
* login
* @param {object} req request object
* @param {object} res response object
* @param {object} db database object
*/
function login(req, res, db) {
function login(req, res) {
accountServices
.login(req.body, db)
.login(req.body)
.then((result) => res.json(result))
.catch((error) => res.status(400).json(error.message));
}
Expand Down
20 changes: 8 additions & 12 deletions src/controllers/productController.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@ const {
* add product
* @param {object} req request object
* @param {object} res response object
* @param {object} db database object
*/
function add(req, res, db) {
function add(req, res) {
accountServices
.getUsername(req.headers['x-api-key'])
.then((owner) => {
Expand All @@ -24,7 +23,7 @@ function add(req, res, db) {
{ owner }
);

return productServices.add(body, db);
return productServices.add(body);
})
.then((result) => res.json(result))
.catch((error) => res.status(400).json(ADD_PRODUCT_FAILED));
Expand All @@ -35,12 +34,11 @@ function add(req, res, db) {
* get all products by owner
* @param {object} req request object
* @param {object} res response object
* @param {object} db database object
*/
function getAll(req, res, db) {
function getAll(req, res) {
accountServices
.getUsername(req.headers['x-api-key'])
.then((owner) => productServices.get(owner, db))
.then(productServices.get)
.then((result) => res.json(result))
.catch((error) => res.status(400).json(NO_PRODUCT));
}
Expand All @@ -50,9 +48,8 @@ function getAll(req, res, db) {
* update product
* @param {object} req request object
* @param {object} res response object
* @param {object} db database object
*/
function update(req, res, db) {
function update(req, res) {
accountServices
.getUsername(req.headers['x-api-key'])
.then((owner) => {
Expand All @@ -62,7 +59,7 @@ function update(req, res, db) {
{ owner }
);

return productServices.update(body, db);
return productServices.update(body);
})
.then((result) => res.json(result))
.catch((error) => res.status(400).json(UPDATE_PRODUCT_FAILED));
Expand All @@ -73,9 +70,8 @@ function update(req, res, db) {
* remove product
* @param {object} req request object
* @param {object} res response object
* @param {object} db database object
*/
function remove(req, res, db) {
function remove(req, res) {
accountServices
.getUsername(req.headers['x-api-key'])
.then((owner) => {
Expand All @@ -85,7 +81,7 @@ function remove(req, res, db) {
{ owner }
);

return productServices.remove(body, db);
return productServices.remove(body);
})
.then((result) => res.json(result))
.catch((error) => res.status(400).json(REMOVE_PRODUCT_FAILED));
Expand Down
31 changes: 28 additions & 3 deletions src/controllers/productController.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ const jwt = require('../utils/jwt');

describe('Product Controller', () => {
const PRODUCT_URL = '/api/store/products';
const apiKey = jwt.generate('testUser');

describe('add() function', () => {
const apiKey = jwt.generate('testUser');

const VALID_ACCOUNT = {
productName: 'Test Product',
productDesc: 'This is the test product',
Expand Down Expand Up @@ -110,7 +109,33 @@ describe('Product Controller', () => {
.end((err, res) => {
expect(err).to.not.exist;
expect(res.status).to.equal(200);
expect(res.body).to.deep.equal('OK');
expect(res.body).to.equal('OK');
done();
});
});
});


describe('getAll() function', () => {
it('should fail to get - missing api-key', (done) => {
request(app)
.get(PRODUCT_URL)
.end((err, res) => {
expect(err).to.not.exist;
expect(res.status).to.equal(400);
expect(res.body).to.equal('NO_PRODUCT');
done();
});
});

it('should succeed', (done) => {
request(app)
.get(PRODUCT_URL)
.set('x-api-key', apiKey)
.end((err, res) => {
expect(err).to.not.exist;
expect(res.status).to.equal(200);
expect(res.body).to.be.an.instanceof(Array);
done();
});
});
Expand Down
14 changes: 14 additions & 0 deletions src/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const monk = require('monk');
const getenv = require('getenv');

const mongoUri = getenv('NODE_ENV') !== 'test' ?
getenv('MONGO_URI') :
getenv('MONGO_URI_TEST');

const db = monk(mongoUri);

// create mongo index
// const products = db.get('products');
// products.createIndex('productId');

module.exports = db;
13 changes: 1 addition & 12 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,13 @@ const compression = require('compression');
const helmet = require('helmet');
const bodyParser = require('body-parser');
const sslRedirect = require('heroku-ssl-redirect');
const monk = require('monk');
const getenv = require('getenv');
const cors = require('cors');

const routes = require('./routes');
const logger = require('./utils/logger');

const { SERVER_ERROR } = require('./constants/responses');

const mongoUri = getenv('NODE_ENV') !== 'test' ?
getenv('MONGO_URI') :
getenv('MONGO_URI_TEST');

const db = monk(mongoUri);
const port = getenv('PORT') || 8080;
const app = express();

Expand All @@ -31,12 +24,8 @@ app.use(bodyParser.urlencoded({ extended: false }));
app.use('/healthcheck', require('express-healthcheck')());
app.get('/version', require('version-healthcheck'));

// create mongo index
// const products = db.get('products');
// products.createIndex('productId', { unique: true });

// pass db to the route
routes(app, db);
routes(app);

app.use((err, req, res, next) => {
logger.error('--- server error ---', err);
Expand Down
19 changes: 8 additions & 11 deletions src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,17 @@ const accountController = require('./controllers/accountController');
const productController = require('./controllers/productController');
const { version } = require('../package.json');

const route = (app, db) => {
const route = (app) => {
router.get('/version', (req, res) => res.json(version));

router.post('/account/create', (req, res) =>
accountController.create(req, res, db));
/* Accounts */
router.post('/account/create', accountController.create);
router.post('/account/login', accountController.login);
router.post('/account/verify', accountController.verify);

router.post('/account/login', (req, res) =>
accountController.login(req, res, db));

router.post('/account/verify', (req, res) =>
accountController.verify(req, res, db));

router.post('/store/products', (req, res) =>
productController.add(req, res, db));
/* Products */
router.get('/store/products', productController.getAll);
router.post('/store/products', productController.add);

/* General */
app.use('/api', router);
Expand Down
17 changes: 11 additions & 6 deletions src/services/accountServices.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const db = require('../db');
const Account = require('../models/account');
const jwt = require('../utils/jwt');
const {
Expand All @@ -6,22 +7,23 @@ const {
ACCOUNT_NOT_FOUND
} = require('../constants/responses');

const ACCOUNT_COLLECTION = 'accounts';


/**
* create account
* @param {object} body request body
* @param {object} db database object
*
* @return {object} json response
*/
async function create(body, db) {
async function create(body) {
const account = new Account(body);

if (!account.isValid()) {
throw new Error(INVALID_PROPS);
}

const collection = db.get('accounts');
const collection = db.get(ACCOUNT_COLLECTION);
const isExisting = (await collection.find({
$or: [{
username: account.username
Expand All @@ -36,6 +38,8 @@ async function create(body, db) {

await collection.insert(account.create());

db.close();

return OK;
}

Expand All @@ -44,19 +48,20 @@ async function create(body, db) {
* login
*
* @param {object} body
* @param {object} db
*
* @return {object} json response
*/
async function login(body, db) {
async function login(body) {
const account = new Account(body);
const collection = db.get('accounts');
const collection = db.get(ACCOUNT_COLLECTION);
const user = await collection.findOne({
username: account.username
}, {
fields: { username: 1, password: 1 }
});

db.close();

if (!user) {
throw new Error(ACCOUNT_NOT_FOUND);
}
Expand Down

0 comments on commit 5009975

Please sign in to comment.