Completed
Push — master ( d93caf...93e6f2 )
by greg
02:20
created

source.js ➔ removeNonEachDataList   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 2
c 1
b 1
f 0
nc 2
nop 1
dl 0
loc 12
rs 9.4285
1
import {Promise} from 'bluebird'
2
import http from 'http' 
3
import https from 'https'
4
import path from 'path'
5
6
import {
7
  config,
8
  cmsData
9
} from '../../'
10
11
export function requestList(obj, tplPath, match, jsonPage) {
12
  var p = new Promise((resolve) => {
13
    cmsData.sql.executeQuery(tplPath, match, jsonPage)
14
      .then((data) => {
15
        if (!jsonPage['abe_source']) {
16
          jsonPage['abe_source'] = {}
17
        }
18
        jsonPage['abe_source'][obj.key] = data
19
        if (!obj.editable) {
20
          if (obj['max-length']) {
21
            jsonPage[obj.key] = data.slice(0, obj['max-length'])
22
          }else {
23
            jsonPage[obj.key] = data
24
          }
25
        } else if (jsonPage[obj.key] == null && obj.prefill) {
26
          if (obj['prefill-quantity'] && obj['max-length']) {
27
            jsonPage[obj.key] = data.slice(0, (obj['prefill-quantity'] > obj['max-length']) ? obj['max-length'] : obj['prefill-quantity'])
28
          }else if (obj['prefill-quantity']) {
29
            jsonPage[obj.key] = data.slice(0, obj['prefill-quantity'])
30
          }else if (obj['max-length']) {
31
            jsonPage[obj.key] = data.slice(0, obj['max-length'])
32
          }else {
33
            jsonPage[obj.key] = data
34
          }
35
        }
36
37
        resolve(jsonPage)
38
      })
39
  })
40
41
  return p
42
}
43
44
export function valueList(obj, match, jsonPage) {
45
  var p = new Promise((resolve) => {
46
    var value = cmsData.sql.getDataSource(match)
47
48
    if(value.indexOf('{') > -1 || value.indexOf('[') > -1) {
49
      try{
50
        value = JSON.parse(value)
51
52
        jsonPage['abe_source'][obj.key] = value
53
      }catch(e){
54
        jsonPage['abe_source'][obj.key] = null
55
        console.log(`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...
56
      }
57
    }
58
    resolve()
59
  })
60
61
  return p
62
}
63
64
export function urlList(obj, tplPath, match, jsonPage) {
65
  var p = new Promise((resolve) => {
66
    if(obj.autocomplete !== true && obj.autocomplete !== 'true') {
67
      var host = obj.sourceString
68
      host = host.split('/')
69
      var httpUse = http
70
      var defaultPort = 80
71
      if(host[0] === 'https:') {
72
        httpUse = https
73
        defaultPort = 443
74
      }
75
      host = host[2].split(':')
76
77
      var pathSource = obj.sourceString.split('//')
78
      if(pathSource[1] != null) {
79
        pathSource = pathSource[1].split('/')
80
        pathSource.shift()
81
        pathSource = '/' + pathSource.join('/')
82
      }else {
83
        pathSource = '/'
84
      }
85
      var options = {
86
        hostname: host[0],
87
        port: (host[1] != null) ? host[1] : defaultPort,
88
        path: pathSource,
89
        method: 'GET',
90
        headers: {
91
          'Content-Type': 'application/x-www-form-urlencoded',
92
          'Content-Length': 0
93
        }
94
      }
95
96
      var body = ''
97
98
      var localReq = httpUse.request(options, (localRes) => {
99
        localRes.setEncoding('utf8')
100
        localRes.on('data', (chunk) => {
101
          body += chunk
102
        })
103
        localRes.on('end', () => {
104
          try {
105
            if(typeof body === 'string') {
106
              var parsedBody = JSON.parse(body)
107
              if(typeof parsedBody === 'object' && Object.prototype.toString.call(parsedBody) === '[object Array]') {
108
                jsonPage['abe_source'][obj.key] = parsedBody
109
              }else if(typeof parsedBody === 'object' && Object.prototype.toString.call(parsedBody) === '[object Object]') {
110
                jsonPage['abe_source'][obj.key] = [parsedBody]
111
              }
112
            }else if(typeof body === 'object' && Object.prototype.toString.call(body) === '[object Array]') {
113
              jsonPage['abe_source'][obj.key] = body
114
            }else if(typeof body === 'object' && Object.prototype.toString.call(body) === '[object Object]') {
115
              jsonPage['abe_source'][obj.key] = body
116
            }
117
          } catch(e) {
118
            console.log(`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...
119
          }
120
          resolve()
121
        })
122
      })
123
124
      localReq.on('error', (e) => {
125
        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...
126
      })
127
128
      // write data to request body
129
      localReq.write('')
130
      localReq.end()
131
      
132
    }else {
133
      jsonPage['abe_source'][obj.key] = obj.sourceString
134
      resolve()
135
    }
136
  })
137
138
  return p
139
}
140
141
export function fileList(obj, tplPath, match, jsonPage) {
142
  var p = new Promise((resolve) => {
143
    jsonPage['abe_source'][obj.key] = cmsData.file.get(path.join(config.root, obj.sourceString))
144
    resolve()
145
  })
146
147
  return p
148
}
149
150
export function nextDataList(tplPath, jsonPage, match, onlyDynamicSelect) {
151
  var p = new Promise((resolve) => {
152
    if(jsonPage['abe_source'] == null) {
153
      jsonPage['abe_source'] = {}
154
    }
155
156
    var obj = cmsData.attributes.getAll(match, jsonPage)
157
    obj = cmsData.attributes.sanitizeSourceAttribute(obj, jsonPage)
158
    
159
    var type = cmsData.sql.getSourceType(obj.sourceString)
160
    
161
    switch (type) {
162
    case 'request':
163
      if (onlyDynamicSelect && obj.editable) {
164
        resolve()
165
      }else {
166
        requestList(obj, tplPath, match, jsonPage)
167
            .then((jsonPage) => {
168
              resolve(jsonPage)
169
            }).catch((e) => {
170
              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...
171
            })
172
      }
173
      break
174
    case 'value':
175
      valueList(obj, match, jsonPage)
176
          .then(() => {
177
            resolve()
178
          }).catch((e) => {
179
            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...
180
          })
181
      break
182
    case 'url':
183
      urlList(obj, tplPath, match, jsonPage)
184
          .then(() => {
185
            resolve()
186
          }).catch((e) => {
187
            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...
188
          })
189
      break
190
    case 'file':
191
      fileList(obj, tplPath, match, jsonPage)
192
          .then(() => {
193
            resolve()
194
          }).catch((e) => {
195
            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...
196
          })
197
      break
198
    default:
199
      resolve()
200
      break
201
    }
202
  })
203
204
  return p
205
}
206
207
export function getDataList(tplPath, text, jsonPage, onlyDynamicSelect = false) {
208
  var p = new Promise((resolve) => {
209
210
    var promises = []
211
    var matches = cmsData.regex.getTagAbeTypeRequest(text)
212
    Array.prototype.forEach.call(matches, (match) => {
213
      promises.push(nextDataList(tplPath, jsonPage, match[0], onlyDynamicSelect))
214
    })
215
216
    Promise.all(promises)
217
      .then(() => {
218
        resolve()
219
      }).catch(function(e) {
220
        console.error('source.js getDataList', e)
221
      })
222
  }).catch(function(e) {
223
    console.error('source.js getDataList', e)
224
  })
225
226
  return p
227
}
228
229
export function removeDataList(text) {
230
231
  return text.replace(cmsData.regex.dataTypeReg, '')
232
}
233
234
export function removeNonEditableDataList(text) {
235
236
  return text.replace(cmsData.regex.nonEditableDataReg, '')
237
}
238
239
export function removeNonEachDataList(text) {
240
  // removing each blocks potentially containing abe data type
241
  let pattEach = /(\{\{#each (\r|\t|\n|.)*?\/each\}\})/g
242
  let textWithNoEach = text.replace(pattEach, '')
243
244
  var match
245
  while (match = cmsData.regex.dataTypeReg.exec(textWithNoEach)) {
246
    text = text.replace(match[0], '')
247
  }
248
249
  return text
250
}
251