File size: 881 Bytes
befd7da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'use strict';

const wrap = require('co-express');

module.exports = setup;

// // //

/**
 * Translation Middleware
 *
 * This function checks if a res.body has been set and will
 * translate all found keys.
 *
 * @param {Object} i18n library configured instance
 * @return {Function} middleware
 */
function setup(i18n) {
  /**
   * Middleware
   * @param  {Object}   req  Express request
   * @param  {Object}   res  Express response
   * @param  {Function} next Express next handler
   * @returns {void}
   */
  return wrap(function* middleware(req, res, next) {
    if (!i18n) {
      throw new Error(
        'Missing i18n dependency, i18n middleware should be initialized with a configured instance of i18n'
      );
    }

    if (res.body) {
      res.body = yield i18n.translate(res.body, req.language);
      return res.json(res.body);
    }

    return next();
  });
}