Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Teste de Lucas Barboza #10

Open
wants to merge 27 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
575de34
First Commit: Project Initialization
LucasBarboza-maker Feb 7, 2023
902fc33
Add: adding express module to the application
LucasBarboza-maker Feb 7, 2023
6b2e731
Add: Mongodb module
LucasBarboza-maker Feb 7, 2023
3071f3c
Chore: Adding lines to gitignore
LucasBarboza-maker Feb 7, 2023
f679ff1
Add: adding mongoose
LucasBarboza-maker Feb 7, 2023
2218e9c
Add: adding dot env lib
LucasBarboza-maker Feb 7, 2023
1cf37e7
Chore: first initialization config
LucasBarboza-maker Feb 7, 2023
e7ee7cf
Chore: create beer model
LucasBarboza-maker Feb 7, 2023
462720d
Chore: Moving db info file
LucasBarboza-maker Feb 7, 2023
ddc69f2
Chore: Migrations
LucasBarboza-maker Feb 7, 2023
3f2c14c
Chore: Initializating Server
LucasBarboza-maker Feb 7, 2023
f3cb37d
Chore: First route done
LucasBarboza-maker Feb 7, 2023
1e91571
Chore: Get by id
LucasBarboza-maker Feb 7, 2023
3d0ab6a
Chore: update route done
LucasBarboza-maker Feb 7, 2023
1f74a01
Chore: done create route
LucasBarboza-maker Feb 7, 2023
e7a4038
Chore: Done deletation route
LucasBarboza-maker Feb 7, 2023
ae4a1a1
Chore: add filter
LucasBarboza-maker Feb 7, 2023
e33e172
Chore: adding sort function
LucasBarboza-maker Feb 7, 2023
019cc2c
Chore: Adding limit to return some fields
LucasBarboza-maker Feb 7, 2023
90f99a7
Chore: adding pagination
LucasBarboza-maker Feb 7, 2023
d4d247b
Chore: adding catch async callback
LucasBarboza-maker Feb 8, 2023
a4d1154
Chore: preparing to production start
LucasBarboza-maker Feb 8, 2023
37f638f
Chore: Error handler
LucasBarboza-maker Feb 8, 2023
9bcd83c
Chore: add regex
LucasBarboza-maker Feb 8, 2023
877eba9
Add: add pm2 package
LucasBarboza-maker Feb 8, 2023
956b03f
Add: Cors Package
LucasBarboza-maker Feb 8, 2023
4187ccd
Chore: Enable Public Cors
LucasBarboza-maker Feb 8, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
config.env
.cache
17 changes: 17 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const express = require('express');
const globalErrorHandler = require('./controllers/errorController');
var cors = require('cors')

const beerRouter = require('./routes/beerRoutes');

const app = express();

app.use(cors())

//Body parser, reading data from body into req.body
app.use(express.json({limit: '10kb'}));
app.use('/api/beers', beerRouter);

app.use(globalErrorHandler)

module.exports = app;
9 changes: 9 additions & 0 deletions controllers/beerControler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const Beer = require('./../models/beerModel');
const factory = require('./handlerFactory');

exports.getAllBeers = factory.getAll(Beer);
exports.getBeer = factory.getOne(Beer);
exports.createBeer = factory.createOne(Beer);
exports.updateBeer = factory.updateOne(Beer);
exports.deleteBeer = factory.deleteOne(Beer);

97 changes: 97 additions & 0 deletions controllers/errorController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
const AppError = require("../utils/appError")

const handleCastErrorDB = err => {
const message = `Invalid ${err.path}: ${err.value}.`
return new AppError(message, 400);
}

const handleDuplicateFieldsDB = err => {
const value = err.errmsg.match(/(["'])(\\?.)*?\1/)[0];
const message = `Duplicate field value: ${value}. Please use another value! `
return new AppError(message, 400);
}

const handleValidationErrorDB = err => {
const errors = Object.values(err.errors).map(el => el.message);

const message = `Invalid input data. ${errors.join('. ')}`;
return new AppError(message, 400);
}


const sendErrorDev = (err, req, res) => {

if (req.originalUrl.startsWith('/api')) {
return res.status(err.statusCode).json({
status: err.status,
error: err,
message: err.message,
stack: err.stack
})
}
return res.status(err.statusCode).render('error', {
title: 'Something went wrong!',
msg: err.message
})


}


const sendErrorProd = (err, req, res) => {
if (req.originalUrl.startsWith('/api')) {

if (err.isOperational) {

return res.status(err.statusCode).json({
status: err.status,
message: err.message,
})

}

return res.status(500).json({
status: 'error',
message: 'Something went very wrong'
})

}


if (err.isOperational) {
return res.status(err.statusCode).render('error', {
title: 'Something went wrong!',
msg: err.message
})

}

return res.status(err.statusCode).render('error', {
title: 'Something went wrong!',
msg: 'Please try again later'
})


}

module.exports = (err, req, res, next) => {
err.statusCode = err.statusCode || 500;
err.status = err.status || 'Error';

if (process.env.NODE_ENV === 'development') {

sendErrorDev(err, req, res);

} else if (process.env.NODE_ENV === 'production') {

let error = err;

if (error.name === 'CastError') error = handleCastErrorDB(error)
if (error.code === 11000) error = handleDuplicateFieldsDB(error);
if (error.name === "ValidationError") error = handleValidationErrorDB(error);

sendErrorProd(error, req, res);

}

};
96 changes: 96 additions & 0 deletions controllers/handlerFactory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const APIFeatures = require("../utils/apiFeatures");
const catchAsync = require("../utils/catchAsync");

exports.getAll = Model => catchAsync(async (req, res, next) => {

try{
let filter = {};
if(req.params.beerId) filter = {tour: req.params.beerId}

const features = new APIFeatures(Model.find(filter), req.query)
.filter()
.sort()
.limitFields()
.paginate()

const doc = await features.query;

res.status(200).json({
status: 'success',
results: doc.length,
data: {
data:doc
}
})
}catch(err){
console.log(err)
}
});


exports.getOne = (Model) => catchAsync(async (req, res, next) => {
let query = Model.findById(req.params.id);

const doc = await query;

if(!doc){
return next(new AppError('No document found with that ID', 404));
}

res.status(200).json({
status: 'success',
data:{
data:doc
}
});

});

exports.updateOne = Model => catchAsync(async (req, res, next) => {


console.log(req.body);
const doc = await Model.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true
})

if(!doc){
return next(new AppError('No document found with that ID', 404))
}

res.status(200).json({
status: 'success',
data: {
data:doc
}
});

});

exports.createOne = Model => catchAsync( async (req, res, next) => {

const doc = await Model.create(req.body);

res.status(201).json({
status:'success',
data:{
data:doc
}
})
});


exports.deleteOne = Model => catchAsync(async (req, res, next) => {

const doc = await Model.findByIdAndDelete(req.params.id)

if(!doc){
return next(new AppError('No document found with that ID', 404))
}

res.status(200).json({
status: 'success',
data: null
});
});
24 changes: 24 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const mongoose = require('mongoose');
const app = require('./app');
const dotenv = require('dotenv');

dotenv.config({path: './config.env'});

const port = process.env.PORT || 3000;

const DB = process.env.DATABASE.replace(
'<PASSWORD>',
process.env.DATABASE_PASSWORD
);

mongoose.set('strictQuery', false);

mongoose.connect(DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log(`Connection established`))


const server = app.listen(port, () => {
console.log(`App running on port: ${port}...`);
})
File renamed without changes.
51 changes: 51 additions & 0 deletions migrations/migrations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const fs = require('fs');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const Beer = require('./../models/BeerModel');

dotenv.config({ path: './config.env' });

const DB = process.env.DATABASE.replace(
'<PASSWORD>',
process.env.DATABASE_PASSWORD
);

mongoose.set('strictQuery', false);


mongoose
.connect(DB, {
useNewUrlParser: true,
})
.then(() => console.log('DB connection successful!'));

// READ JSON FILE
const beers = JSON.parse(fs.readFileSync(`${__dirname}/db.json`, 'utf-8'));

// IMPORT DATA INTO DB
const importData = async () => {
try {
await Beer.create(beers);
console.log('Data successfully loaded!');
} catch (err) {
console.log(err);
}
process.exit();
};

// DELETE ALL DATA FROM DB
const deleteData = async () => {
try {
await Beer.deleteMany();
console.log('Data successfully deleted!');
} catch (err) {
console.log(err);
}
process.exit();
};

if (process.argv[2] === '--import') {
importData();
} else if (process.argv[2] === '--delete') {
deleteData();
}
53 changes: 53 additions & 0 deletions models/BeerModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const mongoose = require('mongoose');


const beerSchema = new mongoose.Schema({
name:{
type:String,
required:[true, "A Beer must have a Name"],
default:"Nameless Beer"
},
abv: {
type: Number,
required:[true, 'A Beer must have IBV'],
},
address:{
type:String,
required:false
},
category:{
type:String,
required:false
},
coordinates:[Number],
country: String,
description:{
type:String,
required:false
},
ibu:{
type:Number,
required:[true, "A Beer must have a IBU"]
},
state:{
type:String,
required:false
},
website:{
type:String,
required:false
}
},
{
toJSON: { virtuals: true },
toObject: {vitruals: true}
}

);

beerSchema.index({name:1});
beerSchema.index({coordinates: '2dsphere'})

const Beer = mongoose.model('Beer', beerSchema);

module.exports = Beer;
Loading