Skip to content

Instantly share code, notes, and snippets.

@diogoazevedos
Created November 6, 2017 18:35
Show Gist options
  • Save diogoazevedos/f8b89c96a0e36400b6d682910c104063 to your computer and use it in GitHub Desktop.
Save diogoazevedos/f8b89c96a0e36400b6d682910c104063 to your computer and use it in GitHub Desktop.
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'));
class UserRepository {
constructor(db) {
this.db = db;
}
first(userId) {
return this.db('users')
.where('id', userId)
.then(rows => rows[0]);
}
}
module.exports = UserRepository;
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