src/server/routes/get-main.js   B
last analyzed

Complexity

Total Complexity 42
Complexity/F 3.82

Size

Lines of Code 176
Function Count 11

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
cc 0
nc 1
dl 0
loc 176
rs 8.295
c 2
b 2
f 0
wmc 42
mnd 2
bc 24
fnc 11
bpm 2.1818
cpm 3.8181
noi 5

2 Functions

Rating   Name   Duplication   Size   Complexity  
C get-main.js ➔ route 0 95 7
C get-main.js ➔ renderAbeAdmin 0 60 16

How to fix   Complexity   

Complexity

Complex classes like src/server/routes/get-main.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import path from 'path'
2
import xss from 'xss'
3
import pkg from '../../../package'
4
5
import {
6
  config,
7
  Page,
8
  cmsData,
9
  cmsTemplates,
10
  coreUtils,
11
  abeExtend,
12
  Manager,
13
  User
14
} from '../../cli'
15
16
import {editor} from '../controllers/editor'
17
import locale from '../helpers/abe-locale'
18
19
function renderAbeAdmin(EditorVariables, obj, filePath) {
20
  var manager = {}
21
  
22
  manager.home = {
23
    files: []//Manager.instance.getList()
24
  }
25
26
  manager.list = Manager.instance.getStructureAndTemplates()
27
  manager.editConfig = EditorVariables.express.req.app.get('config')
28
  manager.config = JSON.stringify(config)
29
    
30
  var _hasBlock = (obj) ? obj.hasBlock : false
31
  var _hasSingleBlock = (obj) ? obj.hasSingleBlock : false
32
  var _preview = (filePath) ? '/abe/page/' + EditorVariables.express.req.params[0] + `?filePath=${EditorVariables.express.req.query.filePath}` : false
33
  var _form = (obj) ? obj.form : false
34
  var _json = (obj) ? obj.json : false
35
  var _filePath = (filePath) ? filePath : false
36
  if (_filePath) {
37
    _filePath = '/' + _filePath.replace(/^\/+/, '')
0 ignored issues
show
Unused Code introduced by
The assignment to variable _filePath seems to be never used. Consider removing it.
Loading history...
38
  }
39
40
  var pageHtml = ''
41
  if(typeof _json !== 'undefined' && _json !== null && typeof _json.abe_meta !== 'undefined' && _json.abe_meta !== null) {
42
43
    var text = cmsTemplates.template.getTemplate(_json.abe_meta.template, _json) 
44
    var page = new Page(_json.abe_meta.template, text, _json, false) 
45
    pageHtml = page.html.replace(/"/g, '"').replace(/'/g, '\'').replace(/<!--/g, '<ABE!--').replace(/-->/g, '--ABE>')
46
  }
47
    
48
  var editorWidth = '33%'
49
  EditorVariables.express.req.headers && EditorVariables.express.req.headers.cookie && EditorVariables.express.req.headers.cookie.split(';').forEach(function(cookie) {
50
    var parts = cookie.match(/(.*?)=(.*)$/)
51
    if ( typeof parts !== 'undefined' && parts !== null && ( parts.length > 2 ) && ( parts[1] === 'editorWidth' ) ) editorWidth = parts[2]
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
52
  })
53
54
  EditorVariables.pageHtml = pageHtml
55
  EditorVariables.test = JSON.stringify(locale)
56
  EditorVariables.text = locale
57
  EditorVariables.preview = _preview
58
  EditorVariables.hasSingleBlock = _hasSingleBlock
59
  EditorVariables.hasBlock = _hasBlock
60
  EditorVariables.form = _form
61
  EditorVariables.json = _json
62
  EditorVariables.manager = manager
63
//  EditorVariables.nonce = '\'nonce-' + EditorVariables.express.res.locals.nonce + '\''
64
  EditorVariables.editorWidth = editorWidth
65
66
  if (_json != null && _json.abe_meta) {
67
    EditorVariables.workflows = User.utils.getUserWorkflow(_json.abe_meta.status)
68
  }
69
70
  EditorVariables = abeExtend.hooks.instance.trigger('afterVariables', EditorVariables)
71
72
  if (filePath != null && filePath.indexOf('.json') > -1) {
73
    EditorVariables.express.res.set('Content-Type', 'application/json')
74
    EditorVariables.express.res.send(JSON.stringify(_json))
75
  }else {
76
    EditorVariables.express.res.render(config.abeEngine, EditorVariables)
77
  }
78
}
79
80
var route = function(req, res, next) {
81
  var filePath = req.originalUrl.replace('/abe/editor', '')
82
  if (filePath === '' || filePath === '/') {
83
    filePath = null
84
  }
85
86
  if(filePath != null){
87
    var testXSS = xss(filePath, {
88
      whiteList: [],
89
      stripIgnoreTag: true
90
    })
91
    if(testXSS !== filePath){
92
      filePath = testXSS
93
    }
94
  }
95
96
  abeExtend.hooks.instance.trigger('beforeRoute', req, res, next)
97
  if(typeof res._header !== 'undefined' && res._header !== null) return
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
98
99
  var isHome = true
100
  var jsonPath = null
101
  var linkPath = null
102
  var template = null
103
  var fileName = null
104
  var folderPath = null
105
106
  var EditorVariables = {
107
    user: res.user,
108
    slugs: Manager.instance.getSlugs(),
109
    express: {
110
      res: res,
111
      req: req
112
    },
113
    filename: fileName,
114
    folderPath: folderPath,
115
    abeUrl: '/abe/editor/',
116
    isHome: isHome,
117
    config: config,
118
    Locales: coreUtils.locales.instance.i18n,
119
    abeVersion: pkg.version
120
  }
121
122
  let p = new Promise((resolve) => {
123
124
    if(filePath != null) {
125
      fileName = path.basename(filePath)
126
      folderPath = path.dirname(filePath)
127
128
      EditorVariables.isHome = false
129
      var filePathTest = cmsData.revision.getDocumentRevision(filePath)
130
      if(typeof filePathTest !== 'undefined' && filePathTest !== null) {
131
        jsonPath = filePathTest.path
132
        linkPath = filePathTest.abe_meta.link
133
        template = filePathTest.abe_meta.template
134
      }
135
136
      if(jsonPath === null || !coreUtils.file.exist(jsonPath)) { 
137
        res.redirect('/abe/editor') 
138
        return 
139
      }
140
141
      var json = {}
142
      if(coreUtils.file.exist(jsonPath)) {
143
        json = cmsData.file.get(jsonPath, 'utf8')
144
      }
145
      var text = cmsTemplates.template.getTemplate(template, json)
146
      editor(text, json, linkPath)
147
        .then((result) => {
148
          resolve(result)
149
        }).catch(function(e) {
150
          console.error(e)
151
        })
152
    }else {
153
      resolve({
154
        json: {},
155
        manager: {}
156
      })
157
    }
158
  }).catch(function(e) {
159
    console.error(e) // "oh, no!"
160
  })
161
162
  p.then((obj) => {
163
    var precontrib = Manager.instance.getPrecontribution()
164
    editor(precontrib.template, obj.json, '', true)
165
      .then((resultPrecontrib) => {
166
        EditorVariables.resultPrecontrib = resultPrecontrib
167
        renderAbeAdmin(EditorVariables, obj, filePath, isHome, template)
0 ignored issues
show
Bug introduced by
The call to renderAbeAdmin seems to have too many arguments starting with isHome.
Loading history...
168
      }).catch(function(e) {
169
        console.error(e)
170
      })
171
  }).catch((e) => {
172
    console.log('error', e)
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
173
  })
174
}
175
176
export default route
177