Skip to content

Commit 58de54f

Browse files
author
Kevyn Bruyere
committed
Upgrade js to be more es6-like, fix small bugs and inconsistencies
1 parent e35b47b commit 58de54f

26 files changed

+103
-95
lines changed

sections/errorhandling/centralizedhandling.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ app.use(async (err: Error, req: Request, res: Response, next: NextFunction) => {
8080
module.exports.handler = new errorHandler();
8181

8282
function errorHandler() {
83-
this.handleError = async function(err) {
83+
this.handleError = async (err) => {
8484
await logger.logError(err);
8585
await sendMailToAdminIfCritical;
8686
await saveInOpsQueueIfCritical;

sections/errorhandling/shuttingtheprocess.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,22 +11,22 @@ Somewhere within your code, an error handler object is responsible for deciding
1111

1212
```javascript
1313
// Assuming developers mark known operational errors with error.isOperational=true, read best practice #3
14-
process.on('uncaughtException', function(error) {
14+
process.on('uncaughtException', (error) => {
1515
errorManagement.handler.handleError(error);
1616
if(!errorManagement.handler.isTrustedError(error))
1717
process.exit(1)
1818
});
1919

2020
// centralized error handler encapsulates error-handling related logic
2121
function errorHandler() {
22-
this.handleError = function (error) {
23-
return logger.logError(err)
22+
this.handleError = (error) => {
23+
return logger.logError(error)
2424
.then(sendMailToAdminIfCritical)
2525
.then(saveInOpsQueueIfCritical)
2626
.then(determineIfOperationalError);
2727
}
2828

29-
this.isTrustedError = function (error) {
29+
this.isTrustedError = (error) => {
3030
return error.isOperational;
3131
}
3232
}

sections/errorhandling/testingerrorflows.md

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Testing ‘happy’ paths is no better than testing failures. Good testing code
1212
```javascript
1313
describe("Facebook chat", () => {
1414
it("Notifies on new chat message", () => {
15-
var chatService = new chatService();
15+
const chatService = new chatService();
1616
chatService.participants = getDisconnectedParticipants();
1717
expect(chatService.sendMessage.bind({ message: "Hi" })).to.throw(ConnectionError);
1818
});
@@ -40,19 +40,18 @@ describe("Facebook chat", () => {
4040
<summary><strong>Javascript</strong></summary>
4141

4242
```javascript
43-
it("Creates new Facebook group", (done) => {
44-
var invalidGroupInfo = {};
45-
httpRequest({
43+
it("Creates new Facebook group", () => {
44+
const invalidGroupInfo = {};
45+
return httpRequest({
4646
method: 'POST',
4747
uri: "facebook.com/api/groups",
4848
resolveWithFullResponse: true,
4949
body: invalidGroupInfo,
5050
json: true
5151
}).then((response) => {
52-
// if we were to execute the code in this block, no error was thrown in the operation above
52+
expect.fail('if we were to execute the code in this block, no error was thrown in the operation above')
5353
}).catch((response) => {
5454
expect(400).to.equal(response.statusCode);
55-
done();
5655
});
5756
});
5857
```

sections/errorhandling/usematurelogger.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ const options = {
3535
};
3636

3737
// Find items logged between today and yesterday.
38-
winston.query(options, function (err, results) {
38+
winston.query(options, (err, results) => {
3939
// execute callback with results
4040
});
4141
```

sections/performance/block-loop.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@ Node handles the Event Loop mostly on a single thread rotating through multiple
66

77
### Example: blocking the event loop
88
Let's take a look at an example from [Node Clinic](https://clinicjs.org/documentation/doctor/05-fixing-event-loop-problem).
9-
```
9+
```javascript
1010
function sleep (ms) {
1111
const future = Date.now() + ms
1212
while (Date.now() < future);
1313
}
1414

15-
server.get('/', function (req, res, next) {
15+
server.get('/', (req, res, next) => {
1616
sleep(30)
1717
res.send({})
1818
next()

sections/performance/nativeoverutil.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,10 @@ The graph below shows the [mean of the benchmarks for a variety of Lodash method
2020

2121
### Code Example – Benchmark test on `_.concat`/`Array.concat`
2222
```javascript
23-
const _ = require('lodash'),
24-
__ = require('underscore'),
25-
Suite = require('benchmark').Suite,
26-
opts = require('./utils'); //cf. https://github.com/Berkmann18/NativeVsUtils/blob/master/utils.js
23+
const _ = require('lodash');
24+
const __ = require('underscore');
25+
const Suite = require('benchmark').Suite;
26+
const opts = require('./utils'); //cf. https://github.com/Berkmann18/NativeVsUtils/blob/master/utils.js
2727

2828
const concatSuite = new Suite('concat', opts);
2929
const array = [0, 1, 2];

sections/production/assigntransactionid.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ A typical log is a warehouse of entries from all components and requests. Upon d
1414
// when receiving a new request, start a new isolated context and set a transaction Id. The following example is using the npm library continuation-local-storage to isolate requests
1515

1616
const { createNamespace } = require('continuation-local-storage');
17-
var session = createNamespace('my session');
17+
const session = createNamespace('my session');
1818

1919
router.get('/:id', (req, res, next) => {
2020
session.set('transactionId', 'some unique GUID');
@@ -25,14 +25,15 @@ router.get('/:id', (req, res, next) => {
2525
// Now any other service or components can have access to the contextual, per-request, data
2626
class someService {
2727
getById(id) {
28-
logger.info(Starting to get something by Id);
28+
logger.info('Starting to get something by Id');
2929
// other logic comes here
3030
}
3131
}
3232

3333
// The logger can now append the transaction-id to each entry so that entries from the same request will have the same value
3434
class logger {
35-
info (message)
36-
{console.log(`${message} ${session.get('transactionId')}`);}
35+
info (message) {
36+
console.log(`${message} ${session.get('transactionId')}`);
37+
}
3738
}
3839
```

sections/production/bestateless.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,13 @@ This approach
1616

1717
```javascript
1818
// Typical mistake 1: saving uploaded files locally on a server
19-
var multer = require('multer'); // express middleware for handling multipart uploads
20-
var upload = multer({ dest: 'uploads/' });
19+
const multer = require('multer'); // express middleware for handling multipart uploads
20+
const upload = multer({ dest: 'uploads/' });
2121

22-
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {});
22+
app.post('/photos/upload', upload.array('photos', 12), (req, res, next) => {});
2323

2424
// Typical mistake 2: storing authentication sessions (passport) in a local file or memory
25-
var FileStore = require('session-file-store')(session);
25+
const FileStore = require('session-file-store')(session);
2626
app.use(session({
2727
store: new FileStore(options),
2828
secret: 'keyboard cat'

sections/production/logrouting.md

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,16 @@ We often think of "separation of concerns" in terms of pieces of code between se
1414

1515
```javascript
1616
const { createLogger, transports, winston } = require('winston');
17-
const winston-mongodb = require('winston-mongodb');
17+
/**
18+
* Requiring `winston-mongodb` will expose
19+
* `winston.transports.MongoDB`
20+
*/
21+
require('winston-mongodb');
1822

1923
// log to two different files, which the application now must be concerned with
2024
const logger = createLogger({
2125
transports: [
2226
new transports.File({ filename: 'combined.log' }),
23-
2427
],
2528
exceptionHandlers: [
2629
new transports.File({ filename: 'exceptions.log' })
@@ -47,13 +50,13 @@ const logger = new winston.Logger({
4750
logger.log('info', 'Test Log Message with some parameter %s', 'some parameter', { anything: 'This is metadata' });
4851
```
4952
Then, in the docker container `daemon.json`:
50-
```javascript
53+
```json5
5154
{
5255
"log-driver": "splunk", // just using Splunk as an example, it could be another storage type
5356
"log-opts": {
5457
"splunk-token": "",
5558
"splunk-url": "",
56-
...
59+
//...
5760
}
5861
}
5962
```

sections/production/setnodeenv.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@ Process environment variables is a set of key-value pairs made available to any
1010

1111
### Code example: Setting and reading the NODE_ENV environment variable
1212

13-
```javascript
13+
```shell script
1414
// Setting environment variables in bash before starting the node process
1515
$ NODE_ENV=development
1616
$ node
17+
```
1718

19+
```javascript
1820
// Reading the environment variable using code
19-
if (process.env.NODE_ENV === production)
21+
if (process.env.NODE_ENV === "production")
2022
useCaching = true;
2123
```
2224

0 commit comments

Comments
 (0)