Skip to content

Commit

Permalink
refactoring: remove source from abe-util
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolaslabbe committed Oct 5, 2016
1 parent d1844cf commit 194c7cf
Show file tree
Hide file tree
Showing 10 changed files with 256 additions and 234 deletions.
5 changes: 3 additions & 2 deletions src/cli/Builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import path from 'path'

import {
Util,
cmsData,
FileParser,
config,
fileUtils,
Expand Down Expand Up @@ -31,7 +32,7 @@ class Builder {
var json = fse.readJsonSync(file.path)
var text = cmsTemplate.template.getTemplate(json.abe_meta.template)

Util.getDataList(fileUtils.removeLast(json.abe_meta.link), text, json)
cmsData.source.getDataList(fileUtils.removeLast(json.abe_meta.link), text, json)
.then(() => {
var page = new Page(json.abe_meta.template, text, json, true)
saveHtml(path.join(root, dest + json.abe_meta.link), page.html)
Expand All @@ -45,7 +46,7 @@ class Builder {
var json = fse.readJsonSync(file.path)
var text = cmsTemplate.template.getTemplate(json.abe_meta.template)

Util.getDataList(fileUtils.removeLast(json.abe_meta.link), text, json)
cmsData.source.getDataList(fileUtils.removeLast(json.abe_meta.link), text, json)
.then(() => {
var page = new Page(json.abe_meta.template, text, json, true)
saveHtml(path.join(root, dest + json.abe_meta.link), page.html)
Expand Down
2 changes: 1 addition & 1 deletion src/cli/cms/Page.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export default class Page {
this._addSource(json)

// We remove the {{abe type=data ...}} from the text
this.template = Util.removeDataList(this.template)
this.template = cmsData.source.removeDataList(this.template)

// It's time to replace the [index] by {{@index}} (concerning each blocks)
this.template = this.template.replace(/\[index\]\./g, '{{@index}}-')
Expand Down
2 changes: 2 additions & 0 deletions src/cli/cms/data/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import attr from './attr'
import fileAttr from './fileAttr'
import * as regex from './regex'
import * as sql from './sql'
import * as source from './source'
import * as revision from './revision'
import * as meta from './meta'

Expand All @@ -11,6 +12,7 @@ export {
,attr
,fileAttr
,sql
,source
,revision
,regex
,meta
Expand Down
241 changes: 241 additions & 0 deletions src/cli/cms/data/source.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
import extend from 'extend'
import clc from 'cli-color'
import fse from 'fs-extra'
import ajaxRequest from 'ajax-request'
import {Promise} from 'es6-promise'
import http from 'http'
import https from 'https'
import path from 'path'

import {
config
,cmsData
,Util
,folderUtils
,fileUtils
,FileParser
,dateSlug
,dateUnslug
,Hooks
,Plugins
} from '../../'

export function requestList(obj, tplPath, match, jsonPage) {
var p = new Promise((resolve, reject) => {
cmsData.sql.executeQuery(tplPath, match, jsonPage)
.then((data) => {
if (!jsonPage['abe_source']) {
jsonPage['abe_source'] = {}
}
jsonPage['abe_source'][obj.key] = data
if (!obj.editable) {
if (obj['max-length']) {
jsonPage[obj.key] = data.slice(0, obj['max-length'])
}else {
jsonPage[obj.key] = data
}
} else if ((typeof jsonPage[obj.key] === 'undefined' || jsonPage[obj.key] === null) && obj.prefill) {
if (obj['prefill-quantity'] && obj['max-length']) {
jsonPage[obj.key] = data.slice(0, (obj['prefill-quantity'] > obj['max-length']) ? obj['max-length'] : obj['prefill-quantity'])
}else if (obj['prefill-quantity']) {
jsonPage[obj.key] = data.slice(0, obj['prefill-quantity'])
}else if (obj['max-length']) {
jsonPage[obj.key] = data.slice(0, obj['max-length'])
}else {
jsonPage[obj.key] = data
}
}

resolve()
})
})

return p
}

export function valueList(obj, match, jsonPage) {
var p = new Promise((resolve, reject) => {
var value = cmsData.sql.getDataSource(match)

if(value.indexOf('{') > -1 || value.indexOf('[') > -1) {
try{
value = JSON.parse(value)

jsonPage['abe_source'][obj.key] = value
}catch(e){
jsonPage['abe_source'][obj.key] = null
console.log(clc.red(`Error ${value}/is not a valid JSON`), `\n${e}`)
}
}
resolve()
})

return p
}

export function urlList(obj, tplPath, match, jsonPage) {
var p = new Promise((resolve, reject) => {
if(obj.autocomplete !== true && obj.autocomplete !== 'true') {
var host = obj.sourceString
host = host.split('/')
var httpUse = http
var defaultPort = 80
if(host[0] === 'https:') {
httpUse = https
defaultPort = 443
}
host = host[2].split(':')

var pathSource = obj.sourceString.split('//')
if(typeof pathSource[1] !== 'undefined' && pathSource[1] !== null) {
pathSource = pathSource[1].split('/')
pathSource.shift()
pathSource = '/' + path.join('/')
}else {
pathSource = '/'
}
var options = {
hostname: host[0],
port: (typeof host[1] !== 'undefined' && host[1] !== null) ? host[1] : defaultPort,
path: pathSource,
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 0
}
}

var body = ''

var localReq = httpUse.request(options, (localRes) => {
localRes.setEncoding('utf8')
localRes.on('data', (chunk) => {
body += chunk
})
localRes.on('end', () => {
try {
if(typeof body === 'string') {
var parsedBody = JSON.parse(body)
if(typeof parsedBody === 'object' && Object.prototype.toString.call(parsedBody) === '[object Array]') {
jsonPage['abe_source'][obj.key] = parsedBody
}else if(typeof parsedBody === 'object' && Object.prototype.toString.call(parsedBody) === '[object Object]') {
jsonPage['abe_source'][obj.key] = [parsedBody]
}
}else if(typeof body === 'object' && Object.prototype.toString.call(body) === '[object Array]') {
jsonPage['abe_source'][obj.key] = body
}else if(typeof body === 'object' && Object.prototype.toString.call(body) === '[object Object]') {
jsonPage['abe_source'][obj.key] = body
}
} catch(e) {
console.log(clc.red(`Error ${obj.sourceString} is not a valid JSON`), `\n${e}`)
}
resolve()
})
})

localReq.on('error', (e) => {
console.log(e)
})

// write data to request body
localReq.write('')
localReq.end()

}else {
jsonPage['abe_source'][obj.key] = obj.sourceString
resolve()
}
})

return p
}

export function fileList(obj, tplPath, match, jsonPage) {
var p = new Promise((resolve, reject) => {
jsonPage['abe_source'][obj.key] = FileParser.getJson(path.join(config.root, obj.sourceString))
resolve()
})

return p
}

export function nextDataList(tplPath, jsonPage, match) {
var p = new Promise((resolve, reject) => {
if(typeof jsonPage['abe_source'] === 'undefined' || jsonPage['abe_source'] === null) {
jsonPage['abe_source'] = {}
}

var obj = Util.getAllAttributes(match, jsonPage)
obj = Util.sanitizeSourceAttribute(obj, jsonPage)

var type = cmsData.sql.getSourceType(obj.sourceString)

switch (type) {
case 'request':
requestList(obj, tplPath, match, jsonPage)
.then(() => {
resolve()
}).catch((e) => {
console.log('[ERROR] source.js requestList', e)
})
break
case 'value':
valueList(obj, match, jsonPage)
.then(() => {
resolve()
}).catch((e) => {
console.log('[ERROR] source.js valueList', e)
})
break
case 'url':
urlList(obj, tplPath, match, jsonPage)
.then(() => {
resolve()
}).catch((e) => {
console.log('[ERROR] source.js urlList', e)
})
break
case 'file':
fileList(obj, tplPath, match, jsonPage)
.then(() => {
resolve()
}).catch((e) => {
console.log('[ERROR] source.js fileList', e)
})
break
default:
resolve()
break
}
})

return p
}

export function getDataList(tplPath, text, jsonPage) {
var p = new Promise((resolve, reject) => {

var promises = []
var matches = cmsData.regex.getTagAbeTypeRequest(text)
Array.prototype.forEach.call(matches, (match) => {
promises.push(nextDataList(tplPath, jsonPage, match[0]))
})

Promise.all(promises)
.then(() => {
resolve()
}).catch(function(e) {
console.error('source.js getDataList', e)
})
}).catch(function(e) {
console.error('source.js getDataList', e)
})

return p
}

export function removeDataList(text) {
var listReg = /({{abe.*type=[\'|\"]data.*}})/g

return text.replace(listReg, '')
}
2 changes: 1 addition & 1 deletion src/cli/cms/operations/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ var create = function(template, pathCreate, name, req, forceJson = {}, duplicate
if (duplicate) {
json = cmsData.removeDuplicateAttr(text, json)
}
text = Util.removeDataList(text)
text = cmsData.source.removeDataList(text)
var resHook = Hooks.instance.trigger('beforeFirstSave', filePath, req.query, json, text)
filePath = resHook.filePath
json = resHook.json
Expand Down
2 changes: 1 addition & 1 deletion src/cli/cms/operations/save.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export function save(url, tplPath, json = null, text = '', type = '', previousSa
text = cmsTemplate.template.getTemplate(fullTpl)
}

Util.getDataList(fileUtils.removeLast(tplUrl.publish.link), text, json)
cmsData.source.getDataList(fileUtils.removeLast(tplUrl.publish.link), text, json)
.then(() => {

json = Hooks.instance.trigger('afterGetDataListOnSave', json)
Expand Down
Loading

0 comments on commit 194c7cf

Please sign in to comment.