diff --git a/.gitignore b/.gitignore index 1a56f43..b720e77 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .idea **/node_modules data +yarn.lock diff --git a/README.md b/README.md index 49b2e56..20a4445 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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. \ No newline at end of file diff --git a/authorization/controllers/authorization.controller.js b/authorization/controllers/authorization.controller.js index e2e935d..618ceaf 100644 --- a/authorization/controllers/authorization.controller.js +++ b/authorization/controllers/authorization.controller.js @@ -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) { diff --git a/common/middlewares/auth.validation.middleware.js b/common/middlewares/auth.validation.middleware.js index 8d7ae8f..147a550 100644 --- a/common/middlewares/auth.validation.middleware.js +++ b/common/middlewares/auth.validation.middleware.js @@ -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) { diff --git a/common/services/mongoose.service.js b/common/services/mongoose.service.js index 0e1a83f..63cd14a 100644 --- a/common/services/mongoose.service.js +++ b/common/services/mongoose.service.js @@ -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); diff --git a/index.js b/index.js index 6996155..17f867a 100644 --- a/index.js +++ b/index.js @@ -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(); } diff --git a/package.json b/package.json index 5e8c178..2c8088b 100644 --- a/package.json +++ b/package.json @@ -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" } } diff --git a/users/models/users.model.js b/users/models/users.model.js index 0f3a5e3..553aaf2 100644 --- a/users/models/users.model.js +++ b/users/models/users.model.js @@ -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 {