Skip to content

Instantly share code, notes, and snippets.

@Archimidis
Created January 11, 2018 08:47
Show Gist options
  • Select an option

  • Save Archimidis/809f4cda705edc7533b02cb2714bf71f to your computer and use it in GitHub Desktop.

Select an option

Save Archimidis/809f4cda705edc7533b02cb2714bf71f to your computer and use it in GitHub Desktop.
Sample express.js structure
// UserRepository.js -------------------------------------------------------------------------
// ... implementation
module.exports = UserRepository;
// UserService.js -------------------------------------------------------------------------
// ... implementation
module.exports = UserService;
// createNewUser.js -------------------------------------------------------------------------
const createNewUser = (userService) => (newUser) => {
// ... implementation that uses userService
}
module.exports = createController;
// app.js -------------------------------------------------------------------------
const express = require('express')
const app = express()
const UserRepository = require('./UserRepository');
const UserService = require('./UserService');
// initialize db and everything
const userRepository = new UserRepository();
const userservice = new UserService(userRepository);
const createNewUser = require('./createNewUser')(userservice);
app.post('/register', (req, res) => {
const newUser = req.body;
// prepare other args as well
createNewUser(newUser)
.then(result => res.json({ /* ... */ })
.catch(error => res.json({ /* ... */ });
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
// Test: createNewUser.spec.js -------------------------------------------------------------------------
describe('createNewUser', function() {
it('will fail when insert new user', function() {
const userServiceStub = {
getByEmail() {
return Promise.resolve('[email protected]');
},
insertUser(user) {
return Promise.reject({ /* error props */ });
}
};
const result = createNewUser(userservice))({ /* user data */ })
// assert on result ...
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment