Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nato-re committed Oct 22, 2021
0 parents commit b0b3f21
Show file tree
Hide file tree
Showing 17 changed files with 4,535 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*/models/index.js
*/migrations/*
3 changes: 3 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "eslint-config-trybe-backend"
}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
.env
8 changes: 8 additions & 0 deletions .sequelizerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const path = require('path');

module.exports = {
'config': path.resolve('src/sequelize/config/', 'config.js'),
'models-path': path.resolve('src/', 'models'),
'migrations-path': path.resolve('src/sequelize/', 'migrations'),
'seeders-path': path.resolve('src/sequelize/', 'seeders')
}
4,276 changes: 4,276 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

29 changes: 29 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha tests",
"start": "node src/api/server",
"dev": "nodemon src/api/server"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"chai": "^4.3.4",
"chai-http": "^4.3.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"eslint-config-trybe-backend": "^1.0.4",
"express": "^4.17.1",
"express-rescue": "^1.1.31",
"mocha": "^9.1.3",
"nodemon": "^2.0.14",
"pg": "^8.7.1",
"pg-hstore": "^2.3.4",
"sequelize": "^6.7.0",
"sinon": "^11.1.2"
}
}
12 changes: 12 additions & 0 deletions src/api/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const express = require('express');
const rescue = require('express-rescue');
const UserController = require('../controllers/user');
const errorMiddleware = require('../middlewares/error');

const app = express();

app.get('/users', rescue(UserController));

app.use(errorMiddleware);

module.exports = app;
5 changes: 5 additions & 0 deletions src/api/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const app = require('./app');

const PORT = 3000;

app.listen(PORT, () => console.log(`Rodando na porta ${PORT}`));
6 changes: 6 additions & 0 deletions src/controllers/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const { User } = require('../models');

module.exports = async (_req, res) => {
const users = await User.findAll();
res.status(200).json(users);
};
4 changes: 4 additions & 0 deletions src/middlewares/error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = (err, _req, res, _next) => {
console.log(err);
res.status(500).json({ message: 'Deu bom não, erro interno' });
};
37 changes: 37 additions & 0 deletions src/models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../sequelize/config/config.js')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});

Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
25 changes: 25 additions & 0 deletions src/models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const {
Model,
} = require('sequelize');

module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(_models) {
// define association here
}
}
User.init({
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING,
}, {
sequelize,
modelName: 'User',
});
return User;
};
23 changes: 23 additions & 0 deletions src/sequelize/config/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module.exports = {
development: {
username: 'root',
password: null,
database: 'database_development',
host: '127.0.0.1',
dialect: 'mysql',
},
test: {
username: 'root',
password: null,
database: 'database_test',
host: '127.0.0.1',
dialect: 'mysql',
},
production: {
username: 'root',
password: null,
database: 'database_test',
host: '127.0.0.1',
dialect: 'mysql',
},
};
32 changes: 32 additions & 0 deletions src/sequelize/migrations/20211020194502-create-user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
firstName: {
type: Sequelize.STRING,
},
lastName: {
type: Sequelize.STRING,
},
email: {
type: Sequelize.STRING,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Users');
},
};
22 changes: 22 additions & 0 deletions src/sequelize/seeders/20211020200523-demo-user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module.exports = {
up: (queryInterface, _Sequelize) => queryInterface.bulkInsert('Users', [{
firstName: 'John',
lastName: 'Doe',
email: 'example@example.com',
createdAt: new Date(),
updatedAt: new Date(),
}, {
firstName: 'Leandro',
lastName: 'Karnal',
email: 'leandro.karnal@bol.com',
createdAt: new Date(),
updatedAt: new Date(),
}, {
firstName: 'Brené',
lastName: 'Brown',
email: 'brene.brown@gmail.com',
createdAt: new Date(),
updatedAt: new Date(),
}]),
down: (queryInterface, _Sequelize) => queryInterface.bulkDelete('Users', null, {}),
};
40 changes: 40 additions & 0 deletions tests/getUser.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const chai = require('chai');
const sinon = require('sinon');
const app = require('../src/api/app');
const { User } = require('../src/models');

const chaiHttp = require('chai-http');
chai.use(chaiHttp);

const { expect } = chai;

describe('Resposta do endpoint GET /users', () => {
let response;

const findAllMock = [{
id: 1,
firstName: 'John',
lastName: 'Doe',
email: 'example@example.com',
createdAt: "2021-10-21T18:02:44.106Z",
updatedAt: "2021-10-21T18:02:44.106Z",
}]

before(async () => {
sinon.stub(User, 'findAll').resolves(findAllMock);

response = await chai.request(app).get('/users');
});

after(async () => {
User.findAll.restore();
});

it('deve retornar um array', () => {
expect(response.body).to.be.an('array');
});
it('deve retornar um array de objetos idêntico ao usado no Stub', () => {
expect(response.body).to.deep.equal(findAllMock);
});

})
9 changes: 9 additions & 0 deletions utils/testSequelizeConnection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const Sequelize = require('sequelize');
const configToTest = require('../src/sequelize/config/config').development;

const sequelize = new Sequelize(configToTest);

sequelize
.authenticate()
.then(() => console.log('Conexão foi estabelecida com sucesso.'))
.catch((err) => console.log('Não foi possível conectar com o banco de dados: \n', err));

0 comments on commit b0b3f21

Please sign in to comment.