Completed
Push — master ( d1844c...194c7c )
by
unknown
03:08
created

source.js ➔ ... ➔ ???   B

Complexity

Conditions 1
Paths 12

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
nc 12
dl 0
loc 28
rs 8.8571
nop 2
1
import extend from 'extend'
2
import clc from 'cli-color'
3
import fse from 'fs-extra'
4
import ajaxRequest from 'ajax-request'
5
import {Promise} from 'es6-promise'
6
import http from 'http' 
7
import https from 'https'
8
import path from 'path'
9
10
import {
11
  config
12
  ,cmsData
13
  ,Util
14
  ,folderUtils
0 ignored issues
show
Unused Code introduced by
The variable folderUtils seems to be never used. Consider removing it.
Loading history...
15
  ,fileUtils
0 ignored issues
show
Unused Code introduced by
The variable fileUtils seems to be never used. Consider removing it.
Loading history...
16
  ,FileParser
17
  ,dateSlug
0 ignored issues
show
Unused Code introduced by
The variable dateSlug seems to be never used. Consider removing it.
Loading history...
18
  ,dateUnslug
0 ignored issues
show
Unused Code introduced by
The variable dateUnslug seems to be never used. Consider removing it.
Loading history...
19
  ,Hooks
0 ignored issues
show
Unused Code introduced by
The variable Hooks seems to be never used. Consider removing it.
Loading history...
20
  ,Plugins
0 ignored issues
show
Unused Code introduced by
The variable Plugins seems to be never used. Consider removing it.
Loading history...
21
} from '../../'
22
23
export function requestList(obj, tplPath, match, jsonPage) {
24
  var p = new Promise((resolve, reject) => {
0 ignored issues
show
Unused Code introduced by
The parameter reject is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
25
    cmsData.sql.executeQuery(tplPath, match, jsonPage)
26
      .then((data) => {
27
        if (!jsonPage['abe_source']) {
28
          jsonPage['abe_source'] = {}
29
        }
30
        jsonPage['abe_source'][obj.key] = data
31
        if (!obj.editable) {
32
          if (obj['max-length']) {
33
            jsonPage[obj.key] = data.slice(0, obj['max-length'])
34
          }else {
35
            jsonPage[obj.key] = data
36
          }
37
        } else if ((typeof jsonPage[obj.key] === 'undefined' || jsonPage[obj.key] === null) && obj.prefill) {
38
          if (obj['prefill-quantity'] && obj['max-length']) {
39
            jsonPage[obj.key] = data.slice(0, (obj['prefill-quantity'] > obj['max-length']) ? obj['max-length'] : obj['prefill-quantity'])
40
          }else if (obj['prefill-quantity']) {
41
            jsonPage[obj.key] = data.slice(0, obj['prefill-quantity'])
42
          }else if (obj['max-length']) {
43
            jsonPage[obj.key] = data.slice(0, obj['max-length'])
44
          }else {
45
            jsonPage[obj.key] = data
46
          }
47
        }
48
49
        resolve()
50
      })
51
  })
52
53
  return p
54
}
55
56
export function valueList(obj, match, jsonPage) {
57
  var p = new Promise((resolve, reject) => {
0 ignored issues
show
Unused Code introduced by
The parameter reject is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
58
    var value = cmsData.sql.getDataSource(match)
59
60
    if(value.indexOf('{') > -1 || value.indexOf('[') > -1) {
61
      try{
62
        value = JSON.parse(value)
63
64
        jsonPage['abe_source'][obj.key] = value
65
      }catch(e){
66
        jsonPage['abe_source'][obj.key] = null
67
        console.log(clc.red(`Error ${value}/is not a valid JSON`),  `\n${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...
68
      }
69
    }
70
    resolve()
71
  })
72
73
  return p
74
}
75
76
export function urlList(obj, tplPath, match, jsonPage) {
77
  var p = new Promise((resolve, reject) => {
0 ignored issues
show
Unused Code introduced by
The parameter reject is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
78
    if(obj.autocomplete !== true && obj.autocomplete !== 'true') {
79
      var host = obj.sourceString
80
      host = host.split('/')
81
      var httpUse = http
82
      var defaultPort = 80
83
      if(host[0] === 'https:') {
84
        httpUse = https
85
        defaultPort = 443
86
      }
87
      host = host[2].split(':')
88
89
      var pathSource = obj.sourceString.split('//')
90
      if(typeof pathSource[1] !== 'undefined' && pathSource[1] !== null) {
91
        pathSource = pathSource[1].split('/')
92
        pathSource.shift()
93
        pathSource = '/' + path.join('/')
94
      }else {
95
        pathSource = '/'
96
      }
97
      var options = {
98
        hostname: host[0],
99
        port: (typeof host[1] !== 'undefined' && host[1] !== null) ? host[1] : defaultPort,
100
        path: pathSource,
101
        method: 'GET',
102
        headers: {
103
          'Content-Type': 'application/x-www-form-urlencoded',
104
          'Content-Length': 0
105
        }
106
      }
107
108
      var body = ''
109
110
      var localReq = httpUse.request(options, (localRes) => {
111
        localRes.setEncoding('utf8')
112
        localRes.on('data', (chunk) => {
113
          body += chunk
114
        })
115
        localRes.on('end', () => {
116
          try {
117
            if(typeof body === 'string') {
118
              var parsedBody = JSON.parse(body)
119
              if(typeof parsedBody === 'object' && Object.prototype.toString.call(parsedBody) === '[object Array]') {
120
                jsonPage['abe_source'][obj.key] = parsedBody
121
              }else if(typeof parsedBody === 'object' && Object.prototype.toString.call(parsedBody) === '[object Object]') {
122
                jsonPage['abe_source'][obj.key] = [parsedBody]
123
              }
124
            }else if(typeof body === 'object' && Object.prototype.toString.call(body) === '[object Array]') {
125
              jsonPage['abe_source'][obj.key] = body
126
            }else if(typeof body === 'object' && Object.prototype.toString.call(body) === '[object Object]') {
127
              jsonPage['abe_source'][obj.key] = body
128
            }
129
          } catch(e) {
130
            console.log(clc.red(`Error ${obj.sourceString} is not a valid JSON`),  `\n${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...
131
          }
132
          resolve()
133
        })
134
      })
135
136
      localReq.on('error', (e) => {
137
        console.log(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...
138
      })
139
140
      // write data to request body
141
      localReq.write('')
142
      localReq.end()
143
      
144
    }else {
145
      jsonPage['abe_source'][obj.key] = obj.sourceString
146
      resolve()
147
    }
148
  })
149
150
  return p
151
}
152
153
export function fileList(obj, tplPath, match, jsonPage) {
154
  var p = new Promise((resolve, reject) => {
0 ignored issues
show
Unused Code introduced by
The parameter reject is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
155
    jsonPage['abe_source'][obj.key] = FileParser.getJson(path.join(config.root, obj.sourceString))
156
    resolve()
157
  })
158
159
  return p
160
}
161
162
export function nextDataList(tplPath, jsonPage, match) {
163
  var p = new Promise((resolve, reject) => {
0 ignored issues
show
Unused Code introduced by
The parameter reject is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
164
    if(typeof jsonPage['abe_source'] === 'undefined' || jsonPage['abe_source'] === null) {
165
      jsonPage['abe_source'] = {}
166
    }
167
168
    var obj = Util.getAllAttributes(match, jsonPage)
169
    obj = Util.sanitizeSourceAttribute(obj, jsonPage)
170
    
171
    var type = cmsData.sql.getSourceType(obj.sourceString)
172
173
    switch (type) {
174
    case 'request':
175
      requestList(obj, tplPath, match, jsonPage)
176
          .then(() => {
177
            resolve()
178
          }).catch((e) => {
179
            console.log('[ERROR] source.js requestList', 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...
180
          })
181
      break
182
    case 'value':
183
      valueList(obj, match, jsonPage)
184
          .then(() => {
185
            resolve()
186
          }).catch((e) => {
187
            console.log('[ERROR] source.js valueList', 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...
188
          })
189
      break
190
    case 'url':
191
      urlList(obj, tplPath, match, jsonPage)
192
          .then(() => {
193
            resolve()
194
          }).catch((e) => {
195
            console.log('[ERROR] source.js urlList', 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...
196
          })
197
      break
198
    case 'file':
199
      fileList(obj, tplPath, match, jsonPage)
200
          .then(() => {
201
            resolve()
202
          }).catch((e) => {
203
            console.log('[ERROR] source.js fileList', 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...
204
          })
205
      break
206
    default:
207
      resolve()
208
      break
209
    }
210
  })
211
212
  return p
213
}
214
215
export function getDataList(tplPath, text, jsonPage) {
216
  var p = new Promise((resolve, reject) => {
0 ignored issues
show
Unused Code introduced by
The parameter reject is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
217
218
    var promises = []
219
    var matches = cmsData.regex.getTagAbeTypeRequest(text)
220
    Array.prototype.forEach.call(matches, (match) => {
221
      promises.push(nextDataList(tplPath, jsonPage, match[0]))
222
    })
223
224
    Promise.all(promises)
225
      .then(() => {
226
        resolve()
227
      }).catch(function(e) {
228
        console.error('source.js getDataList', e)
229
      })
230
  }).catch(function(e) {
231
    console.error('source.js getDataList', e)
232
  })
233
234
  return p
235
}
236
237
export function removeDataList(text) {
238
  var listReg = /({{abe.*type=[\'|\"]data.*}})/g
239
240
  return text.replace(listReg, '')
241
}