Skip to content

Commit f65449d

Browse files
committed
Update Post “2019-02-27-how-to-international-api-i18n-validation-in-node-js-for-your-api”
1 parent 7e47ac0 commit f65449d

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

content/blog/2019-02-27-how-to-international-api-i18n-validation-in-node-js-for-your-api.md

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ Finally, let’s create the server.js file:
9898
touch server.js
9999
```
100100

101-
Let’s now get express going by modifying the ```server.js```
101+
Let’s now get express going by modifying the `server.js`
102102

103103
```javascript
104104
// Import dependencies
@@ -230,7 +230,7 @@ req.polyglot.extend(messages.en)
230230
next()
231231
}
232232
```
233-
If you remember, our `server.js` uses the `createLocaleMiddleware` to set the current locale, which lives on ```req.locale.language```.
233+
If you remember, our `server.js` uses the `createLocaleMiddleware` to set the current locale, which lives on `req.locale.language`.
234234

235235
So we get that value, and for our use case, check if it is _es_ for spanish or _en_ for english (our default in case it’s neither), and load the proper messages for the language, which are added to the Express’ ‘req’ object through polyglot’s _extend_ function.
236236

@@ -394,7 +394,7 @@ return fromEntries(errArr)
394394

395395
In this code, we’re receiving both the error Object created with `express-validator` (which we’ll extract from the `req` object with the `validationResult` function in a bit), and the Express’ `req` object.
396396

397-
We’re creating an Array from the errObj, and then, for each entry, we’re taking the string we set as the error variable, and comparing it with the keys from the translation messages, changing the string in the `errArr` _(each "err[1].msg")_ to the actual phrase in polyglot in the desired language _(each "phrase")_.
397+
We’re creating an `Array` from the `errObj`, and then, for each entry, we’re taking the string we set as the error variable, and comparing it with the keys from the translation messages, changing the string in the `errArr` _(each "err[1].msg")_ to the actual phrase in polyglot in the desired language _(each "phrase")_.
398398

399399
Finally, we use the imported `fromEntries` function, to convert the Array back into an Object and return it.
400400

@@ -419,9 +419,33 @@ next()
419419

420420
In this code we receive the regular `req, res, next` from Express, and we first verify if there were any errors using express-validator’s `validationResult`.
421421
Then, we check if there are errors, and if there are any, we return them with Express’ response.
422-
Check that return closely, as you can see, we send the results of the `translateMessages` function that is receiving the `validationErrors`, and the req object.
422+
Check that return closely, as you can see, we send the results of the `translateMessages` function that is receiving the `validationErrors`, and the `req` object.
423423
We also have an `else`, that when there are no validation errors, calls `next()` to continue to the next Express middleware.
424424

425+
### Sending the errors
426+
So we're able to manage the errors by converting them from the string to their translated version, and packaging it in an object, ready to be sent back to the user if needed.
427+
428+
Now, we just need to use that file!
429+
Let's go back to our `auth.routes.js` file and make use of this new function by importing it:
430+
```javascript
431+
import { procErr } from '../utilities/processErrors'
432+
```
433+
434+
As I mentioned earlier, we built it as an Express Middleware, so we can just add it inside of our chain of events
435+
436+
And then using it in the actual routes:
437+
```javascript
438+
// Routes =============================================================
439+
module.exports = router => {
440+
441+
// POST route to mock a login endpoint
442+
router.post("/api/login", validator('login'), procErr)
443+
444+
// POST route to mock a forgotten password endpoint
445+
router.post("/api/forgot-password", validator('forgotPassword'), procErr)
446+
447+
}
448+
```
425449

426450
### Moving past errors
427451

@@ -450,6 +474,8 @@ exports.login = (req, res) => {
450474
// If no validation errors, get the req.body objects that were validated and are needed
451475
const { email, password } = req.body
452476

477+
// Here, we would make use of that data, validating it against our database, creating a JWT token, etc...
478+
453479
// Since all the validations passed, we send the loginSuccessful message, which would normally include a JWT or some other form of authorization
454480
return res.status(200).send({ auth: true, message: req.polyglot.t('loginSuccessful'), token: null })
455481
}
@@ -458,6 +484,8 @@ exports.forgotPassword = (req, res) => {
458484
// If no validation errors, get the req.body objects that were validated and are needed
459485
const { email } = req.body
460486

487+
// Here, we would make use of that data, validating it against our database, creating a JWT token, etc...
488+
461489
// Since all the validations passed, we send the emailSent message
462490
return res.status(200).send({ auth: true, message: req.polyglot.t('emailSent') })
463491
}
@@ -476,17 +504,18 @@ It should now look something like this:
476504

477505
```javascript
478506
import { validator } from '../validator/auth.validator'
507+
import { procErr } from '../utilities/processErrors'
479508
import { login,
480509
forgotPassword } from '../controller/auth.controller'
481510

482511
// Routes =============================================================
483512
module.exports = router => {
484513

485514
// POST route to mock a login endpoint
486-
router.post("/api/login", validator('login'), login)
515+
router.post("/api/login", validator('login'), procErr, login)
487516

488517
// POST route to mock a forgotten password endpoint
489-
router.post("/api/forgot-password", validator('forgotPassword'), forgotPassword)
518+
router.post("/api/forgot-password", validator('forgotPassword'), procErr, forgotPassword)
490519

491520

492521
}
@@ -497,3 +526,6 @@ These last functions respond with the success messages when everything is ok!
497526

498527
So that's it!
499528
Now, Express responds properly whether your `headers` are set to `es_MX` or `en_US`. Both for error and success messages.
529+
530+
### Testing
531+

0 commit comments

Comments
 (0)