Created
November 6, 2017 18:35
-
-
Save diogoazevedos/f8b89c96a0e36400b6d682910c104063 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const UserRepository = require('./UserRepository.js'); | |
const UserService = require('./UserService.js'); | |
const knex = require('knex'); | |
const express = require('express'); | |
const app = express(); | |
const db = knex({ | |
client: 'mysql', | |
connection: { | |
host: 'localhost', | |
user: 'sample', | |
password: 'secret', | |
database: 'sample', | |
}, | |
}); | |
const userRepository = new UserRepository(db); | |
const userService = new UserService(userRepository); | |
app.get('/users/:user_id', (request, response) => { | |
const userId = request.params.user_id; | |
userService.first(userId) | |
.then((user) => { | |
if (user) { | |
return response.send(user); | |
} | |
response.status(404).send({ | |
error: 'User not found!', | |
}); | |
}); | |
}); | |
app.listen(3000, () => console.log('Server running at port 3000')); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserRepository { | |
constructor(db) { | |
this.db = db; | |
} | |
first(userId) { | |
return this.db('users') | |
.where('id', userId) | |
.then(rows => rows[0]); | |
} | |
} | |
module.exports = UserRepository; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserService { | |
constructor(userRepository) { | |
this.users = userRepository; | |
} | |
first(userId) { | |
return users.first(userId); | |
} | |
} | |
module.exports = UserService; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment