Skip to content

Tutorial updates #1

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

Merged
merged 9 commits into from
Sep 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.idea
**/node_modules
data
yarn.lock
23 changes: 14 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
# REST API Tutorial

This sample is published as part of the blog article at www.toptal.com/blog:

- https://www.toptal.com/nodejs/secure-rest-api-in-nodejs

Visit www.toptal.com/blog and subscribe to our newsletter to read great posts
This sample is published as part of [the corresponding article](https://www.toptal.com/nodejs/secure-rest-api-in-nodejs) at the Toptal Engineering Blog. Visit https://www.toptal.com/developers/blog and subscribe to our newsletter to read great posts!

## Before using

- Please make sure that you have:
- node.js installed (https://nodejs.org/)
- have mongodb installed and running locally (https://www.mongodb.com/)
- Node.js installed (https://nodejs.org/)
- MongoDB installed and running locally (https://www.mongodb.com/)
- Using Windows, just open the terminal at where you installed mongo and run `mongod.exe`
- run npm install in your root project folder
- Run `npm install` or `yarn` in your root project folder

## Usage

To run the project, please use a command line the following:
- npm start
- `npm start`
- It will run the server at port 3600.


Expand All @@ -35,3 +32,11 @@ If you are familiar to docker and you have docker installed on your machine and
### 2020-02-01

I've created a 2020 version of this project using Typescript. If you might be interested on it, please check the following repository: https://github.com/makinhs/expressjs-api-tutorial

### 2020-09-09

- Updated and pruned dependencies.
- Fixed deprecation warnings.
- Leveraged `findOneAndUpdate` to simplify PATCH code.
- Changed default MongoDB server name to `localhost` to simplify first-time setup.
- Checked that it works with the latest version of Node.js, 14.9.0.
2 changes: 1 addition & 1 deletion authorization/controllers/authorization.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ exports.login = (req, res) => {
let hash = crypto.createHmac('sha512', salt).update(refreshId).digest("base64");
req.body.refreshKey = salt;
let token = jwt.sign(req.body, jwtSecret);
let b = new Buffer(hash);
let b = Buffer.from(hash);
let refresh_token = b.toString('base64');
res.status(201).send({accessToken: token, refreshToken: refresh_token});
} catch (err) {
Expand Down
2 changes: 1 addition & 1 deletion common/middlewares/auth.validation.middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ exports.verifyRefreshBodyField = (req, res, next) => {
};

exports.validRefreshNeeded = (req, res, next) => {
let b = new Buffer(req.body.refresh_token, 'base64');
let b = Buffer.from(req.body.refresh_token, 'base64');
let refresh_token = b.toString();
let hash = crypto.createHmac('sha512', req.jwt.refreshKey).update(req.jwt.userId + secret).digest("base64");
if (hash === refresh_token) {
Expand Down
6 changes: 2 additions & 4 deletions common/services/mongoose.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,17 @@ let count = 0;

const options = {
autoIndex: false, // Don't build indexes
reconnectTries: 30, // Retry up to 30 times
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0,
//geting rid off the depreciation errors
// all other approaches are now deprecated by MongoDB:
useNewUrlParser: true,
useUnifiedTopology: true

};
const connectWithRetry = () => {
console.log('MongoDB connection with retry')
mongoose.connect("mongodb://mongo:27017/rest-tutorial", options).then(()=>{
mongoose.connect("mongodb://localhost:27017/rest-tutorial", options).then(()=>{
console.log('MongoDB is connected')
}).catch(err=>{
console.log('MongoDB connection unsuccessful, retry after 5 seconds. ', ++count);
Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ app.use(function (req, res, next) {
res.header('Access-Control-Expose-Headers', 'Content-Length');
res.header('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type, X-Requested-With, Range');
if (req.method === 'OPTIONS') {
return res.send(200);
return res.sendStatus(200);
} else {
return next();
}
Expand Down
8 changes: 2 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,7 @@
"body-parser": "1.19.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"moment": "^2.24.0",
"moment-timezone": "^0.5.27",
"mongoose": "^5.7.9",
"uuid": "^3.3.3",
"swagger-ui-express": "^4.1.2",
"sync-request": "^6.1.0"
"mongoose": "^5.10.3",
"uuid": "^8.3.0"
}
}
18 changes: 4 additions & 14 deletions users/models/users.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,24 +59,14 @@ exports.list = (perPage, page) => {
};

exports.patchUser = (id, userData) => {
return new Promise((resolve, reject) => {
User.findById(id, function (err, user) {
if (err) reject(err);
for (let i in userData) {
user[i] = userData[i];
}
user.save(function (err, updatedUser) {
if (err) return reject(err);
resolve(updatedUser);
});
});
})

return User.findOneAndUpdate({
_id: id
}, userData);
};

exports.removeById = (userId) => {
return new Promise((resolve, reject) => {
User.remove({_id: userId}, (err) => {
User.deleteMany({_id: userId}, (err) => {
if (err) {
reject(err);
} else {
Expand Down