From e3c8933d0ff96ca41adb68eadefb8826ff65c6e5 Mon Sep 17 00:00:00 2001 From: nicolaslabbe Date: Tue, 4 Oct 2016 14:29:09 +0200 Subject: [PATCH] refactor --- src/cli/Builder.js | 6 +- src/cli/cms/data/index.js | 2 +- src/cli/cms/data/sql.js | 815 +++++++++--------- src/cli/cms/operations/abe-create.js | 4 +- src/cli/cms/operations/abe-duplicate.js | 1 - src/cli/cms/operations/save.js | 4 +- .../templates/abe-get-select-template-keys.js | 170 ---- src/cli/cms/templates/abe-template.js | 138 --- src/cli/cms/templates/index.js | 3 + src/cli/cms/templates/template.js | 292 +++++++ src/cli/core/manager/Manager.js | 4 +- src/cli/index.js | 8 +- src/server/controllers/editor.js | 4 +- src/server/controllers/index.js | 1 - src/server/helpers/page.js | 4 +- src/server/middlewares/website.js | 1 - src/server/routes/get-create.js | 1 - src/server/routes/get-list-hooks.js | 1 - src/server/routes/get-list-url.js | 1 - src/server/routes/get-main.js | 4 +- test/fixtures/templates/article-keys.html | 3 + test/request.js | 2 +- test/template.js | 44 +- 23 files changed, 755 insertions(+), 758 deletions(-) delete mode 100644 src/cli/cms/templates/abe-get-select-template-keys.js delete mode 100755 src/cli/cms/templates/abe-template.js create mode 100755 src/cli/cms/templates/template.js create mode 100644 test/fixtures/templates/article-keys.html diff --git a/src/cli/Builder.js b/src/cli/Builder.js index 1539950f..2c378f9f 100755 --- a/src/cli/Builder.js +++ b/src/cli/Builder.js @@ -8,7 +8,7 @@ import { config, fileUtils, fileAttr, - getTemplate, + cmsTemplate, Page } from './' @@ -29,7 +29,7 @@ class Builder { .replace('.' + config.files.templates.extension, '.json') var json = fse.readJsonSync(file.path) - var text = getTemplate(json.abe_meta.template) + var text = cmsTemplate.template.getTemplate(json.abe_meta.template) Util.getDataList(fileUtils.removeLast(json.abe_meta.link), text, json) .then(() => { @@ -43,7 +43,7 @@ class Builder { } else if(file.path.indexOf('.json') > -1){ var json = fse.readJsonSync(file.path) - var text = getTemplate(json.abe_meta.template) + var text = cmsTemplate.template.getTemplate(json.abe_meta.template) Util.getDataList(fileUtils.removeLast(json.abe_meta.link), text, json) .then(() => { diff --git a/src/cli/cms/data/index.js b/src/cli/cms/data/index.js index 567572b5..875a7cc0 100644 --- a/src/cli/cms/data/index.js +++ b/src/cli/cms/data/index.js @@ -1,5 +1,5 @@ import removeDuplicateAttr from './remove-duplicate-attr' -import sql from './sql' +import * as sql from './sql' export { removeDuplicateAttr diff --git a/src/cli/cms/data/sql.js b/src/cli/cms/data/sql.js index d97d0cac..092d5ee2 100755 --- a/src/cli/cms/data/sql.js +++ b/src/cli/cms/data/sql.js @@ -8,489 +8,482 @@ import { getAttr } from '../../' -export default class Sql { - - constructor() { - - } - - static cleanRequest(str, jsonPage) { - var matchFrom = /from .(.*?) / - var matchVariable = /{{([a-zA-Z]*)}}/ - - var matchFromExec = matchFrom.exec(str) - if(typeof matchFromExec !== 'undefined' && matchFromExec !== null - && typeof matchFromExec[1] !== 'undefined' && matchFromExec[1] !== null) { - - var fromMatch - var toReplace = matchFromExec[1] - while (fromMatch = matchVariable.exec(toReplace)) { - try { - var value = eval('jsonPage.' + fromMatch[1]) - if(typeof value !== 'undefined' && value !== null) { - toReplace = toReplace.replace('{{' + fromMatch[1] + '}}', value) - }else { - toReplace = toReplace.replace('{{' + fromMatch[1] + '}}', '') - } - }catch(e) { - } - } - - str = str.replace(matchFromExec[1], toReplace) - } - - var from = /from ([\S\s]+)/.exec(str) - - var matches = from - if(matches[1]) { - var res = matches[1] - var splitAttr = [' where ', ' order by ', ' limit ', ' WHERE ', ' ORDER BY ', ' LIMIT '] - for(var i = 0; i < splitAttr.length; i++) { - if(res.indexOf(splitAttr[i]) > -1) { - res = res.substring(0, res.indexOf(splitAttr[i])) +export function cleanRequest(str, jsonPage) { + var matchFrom = /from .(.*?) / + var matchVariable = /{{([a-zA-Z]*)}}/ + + var matchFromExec = matchFrom.exec(str) + if(typeof matchFromExec !== 'undefined' && matchFromExec !== null + && typeof matchFromExec[1] !== 'undefined' && matchFromExec[1] !== null) { + + var fromMatch + var toReplace = matchFromExec[1] + while (fromMatch = matchVariable.exec(toReplace)) { + try { + var value = eval('jsonPage.' + fromMatch[1]) + if(typeof value !== 'undefined' && value !== null) { + toReplace = toReplace.replace('{{' + fromMatch[1] + '}}', value) + }else { + toReplace = toReplace.replace('{{' + fromMatch[1] + '}}', '') } + }catch(e) { } - var escapedFrom = res.replace(/\//g, '___abe___') - escapedFrom = escapedFrom.replace(/\./g, '___abe_dot___') - escapedFrom = escapedFrom.replace(/-/g, '___abe_dash___') - str = str.replace(res, escapedFrom) } - str = str.replace(/``/g, '\'\'') - - return str + str = str.replace(matchFromExec[1], toReplace) } - static handleSqlRequest(str, jsonPage) { - var cleanRequest = Sql.cleanRequest(str, jsonPage) - var request = parse(cleanRequest) - var reconstructSql = '' + var from = /from ([\S\s]+)/.exec(str) - // SQL TYPE - var type = '' - if(typeof request.type !== 'undefined' && request.type !== null) { - type = request.type - } - reconstructSql += `${type} ` - - // SQL COLUMNS - var columns = [] - if(typeof request.columns !== 'undefined' && request.columns !== null) { - if(request.columns === '*') { - columns.push('*') - }else { - Array.prototype.forEach.call(request.columns, (item) => { - columns.push(item.expr.column) - }) + var matches = from + if(matches[1]) { + var res = matches[1] + var splitAttr = [' where ', ' order by ', ' limit ', ' WHERE ', ' ORDER BY ', ' LIMIT '] + for(var i = 0; i < splitAttr.length; i++) { + if(res.indexOf(splitAttr[i]) > -1) { + res = res.substring(0, res.indexOf(splitAttr[i])) } } - reconstructSql += `${JSON.stringify(columns)} ` - - // SQL FROM - var from = [] - if(typeof request.from !== 'undefined' && request.from !== null) { + var escapedFrom = res.replace(/\//g, '___abe___') + escapedFrom = escapedFrom.replace(/\./g, '___abe_dot___') + escapedFrom = escapedFrom.replace(/-/g, '___abe_dash___') + str = str.replace(res, escapedFrom) + } - Array.prototype.forEach.call(request.from, (item) => { - from.push(item.table) - }) - }else { - from.push('*') - } - reconstructSql += `from ${JSON.stringify(from)} ` - - var where - if(typeof request.where !== 'undefined' && request.where !== null) { - where = request.where - // where = Sql.recurseWhere(request.where) - // reconstructSql += 'where ' - // Array.prototype.forEach.call(where, (w) => { - // reconstructSql += `${w.operator} ${w.left} ${w.compare} ${w.right} ` - // }) - } + str = str.replace(/``/g, '\'\'') - var limit = -1 - if(typeof request.limit !== 'undefined' && request.limit !== null) { - limit = request.limit[request.limit.length - 1].value - } + return str +} - var orderby - if(typeof request.orderby !== 'undefined' && request.orderby !== null && request.orderby.length > 0) { - orderby = { - column: request.orderby[0].expr.column, - type: request.orderby[0].type - } - reconstructSql += `ORDER BY ${orderby.column} ${orderby.type} ` - } +export function handleSqlRequest(str, jsonPage) { + var req = cleanRequest(str, jsonPage) + var request = parse(req) + var reconstructSql = '' - return { - type: type, - columns: columns, - from: from, - where: where, - string: reconstructSql, - limit: limit, - orderby: orderby - } + // SQL TYPE + var type = '' + if(typeof request.type !== 'undefined' && request.type !== null) { + type = request.type } + reconstructSql += `${type} ` - static sortByDateDesc(a, b) { - var dateA = new Date(a.date) - var dateB = new Date(b.date) - if(dateA < dateB) { - return 1 - }else if(dateA > dateB) { - return -1 + // SQL COLUMNS + var columns = [] + if(typeof request.columns !== 'undefined' && request.columns !== null) { + if(request.columns === '*') { + columns.push('*') + }else { + Array.prototype.forEach.call(request.columns, (item) => { + columns.push(item.expr.column) + }) } - return 0 } + reconstructSql += `${JSON.stringify(columns)} ` - static shuffle(array) { - var currentIndex = array.length, temporaryValue, randomIndex + // SQL FROM + var from = [] + if(typeof request.from !== 'undefined' && request.from !== null) { - // While there remain elements to shuffle... - while (0 !== currentIndex) { + Array.prototype.forEach.call(request.from, (item) => { + from.push(item.table) + }) + }else { + from.push('*') + } + reconstructSql += `from ${JSON.stringify(from)} ` + + var where + if(typeof request.where !== 'undefined' && request.where !== null) { + where = request.where + // where = recurseWhere(request.where) + // reconstructSql += 'where ' + // Array.prototype.forEach.call(where, (w) => { + // reconstructSql += `${w.operator} ${w.left} ${w.compare} ${w.right} ` + // }) + } - // Pick a remaining element... - randomIndex = Math.floor(Math.random() * currentIndex) - currentIndex -= 1 + var limit = -1 + if(typeof request.limit !== 'undefined' && request.limit !== null) { + limit = request.limit[request.limit.length - 1].value + } - // And swap it with the current element. - temporaryValue = array[currentIndex] - array[currentIndex] = array[randomIndex] - array[randomIndex] = temporaryValue + var orderby + if(typeof request.orderby !== 'undefined' && request.orderby !== null && request.orderby.length > 0) { + orderby = { + column: request.orderby[0].expr.column, + type: request.orderby[0].type } - - return array + reconstructSql += `ORDER BY ${orderby.column} ${orderby.type} ` } - static sortByDateAsc(a, b) { - var dateA = new Date(a.date) - var dateB = new Date(b.date) - if(dateA > dateB) { - return 1 - }else if(dateA < dateB) { - return -1 - } - return 0 + return { + type: type, + columns: columns, + from: from, + where: where, + string: reconstructSql, + limit: limit, + orderby: orderby } +} + +export function sortByDateDesc(a, b) { + var dateA = new Date(a.date) + var dateB = new Date(b.date) + if(dateA < dateB) { + return 1 + }else if(dateA > dateB) { + return -1 + } + return 0 +} - static getDataSource(str) { - var res = str.substring(str.indexOf('source=') + 8, str.length) +export function shuffle(array) { + var currentIndex = array.length, temporaryValue, randomIndex - var reg = /([^'"]*=[\s\S]*?}})/g - var matches = res.match(reg) - if(typeof matches !== 'undefined' && matches !== null) { - Array.prototype.forEach.call(matches, (match) => { - res = res.replace(match, '') - }) - }else { - res = res.replace('}}', '') - } + // While there remain elements to shuffle... + while (0 !== currentIndex) { - return res.substring(0, res.length-1) + // Pick a remaining element... + randomIndex = Math.floor(Math.random() * currentIndex) + currentIndex -= 1 + + // And swap it with the current element. + temporaryValue = array[currentIndex] + array[currentIndex] = array[randomIndex] + array[randomIndex] = temporaryValue } - /** - * replaces escaped characters with the right ones - * @param {String} statement the from clause - * @return {String} the from sanitized - */ - static sanitizeFromStatement(statement){ - var from = '' - - if(typeof statement !== 'undefined' && statement !== null) { - from = statement[0].replace(/___abe_dot___/g, '.') - from = from.replace(/___abe___/g, '/') - from = from.replace(/___abe_dash___/g, '-') - } + return array +} - return from +export function sortByDateAsc(a, b) { + var dateA = new Date(a.date) + var dateB = new Date(b.date) + if(dateA > dateB) { + return 1 + }else if(dateA < dateB) { + return -1 } + return 0 +} - /** - * calculate the directory to analyze from the from clause - * @param {String} statement the from clause - * @param {String} tplPath the path from the template originator - * @return {string} the directory to analyze - */ - static getFromDirectory(statement, tplPath){ - var pathFromDir = '' - if(typeof tplPath === 'undefined' || tplPath === null || tplPath === ''){ - tplPath = '/' - } +export function getDataSource(str) { + var res = str.substring(str.indexOf('source=') + 8, str.length) - if(statement === '' || statement === '*' || statement === '/') { - pathFromDir = path.join(config.root, config.data.url) - }else if(statement === './') { - pathFromDir = path.join(config.root, config.data.url, tplPath) - }else if(statement.indexOf('/') === 0) { - pathFromDir = path.join(config.root, config.data.url, statement) - }else if(statement.indexOf('/') !== 0) { - pathFromDir = path.join(config.root, config.data.url, tplPath, statement) - } - - return pathFromDir + var reg = /([^'"]*=[\s\S]*?}})/g + var matches = res.match(reg) + if(typeof matches !== 'undefined' && matches !== null) { + Array.prototype.forEach.call(matches, (match) => { + res = res.replace(match, '') + }) + }else { + res = res.replace('}}', '') } - static executeOrderByClause(files, orderby){ - if(typeof orderby !== 'undefined' && orderby !== null) { - if(orderby.column.toLowerCase() === 'random') { - Sql.shuffle(files) - }else if(orderby.column.toLowerCase() === 'date') { - if(orderby.type === 'ASC') { - files.sort(Sql.sortByDateAsc) - }else if(orderby.type === 'DESC') { - files.sort(Sql.sortByDateDesc) - } - } - } + return res.substring(0, res.length-1) +} + +/** + * replaces escaped characters with the right ones + * @param {String} statement the from clause + * @return {String} the from sanitized + */ +export function sanitizeFromStatement(statement){ + var from = '' + + if(typeof statement !== 'undefined' && statement !== null) { + from = statement[0].replace(/___abe_dot___/g, '.') + from = from.replace(/___abe___/g, '/') + from = from.replace(/___abe_dash___/g, '-') + } - return files + return from +} + +/** + * calculate the directory to analyze from the from clause + * @param {String} statement the from clause + * @param {String} tplPath the path from the template originator + * @return {string} the directory to analyze + */ +export function getFromDirectory(statement, tplPath){ + var pathFromDir = '' + if(typeof tplPath === 'undefined' || tplPath === null || tplPath === ''){ + tplPath = '/' } - static executeFromClause(statement, pathFromClause){ - var from = Sql.sanitizeFromStatement(statement) + if(statement === '' || statement === '*' || statement === '/') { + pathFromDir = path.join(config.root, config.data.url) + }else if(statement === './') { + pathFromDir = path.join(config.root, config.data.url, tplPath) + }else if(statement.indexOf('/') === 0) { + pathFromDir = path.join(config.root, config.data.url, statement) + }else if(statement.indexOf('/') !== 0) { + pathFromDir = path.join(config.root, config.data.url, tplPath, statement) + } - // if the from clause ends with a dot, we won't recurse the directory analyze - if(from.slice(-1) === '.'){ - from = from.slice(0, -1) - } - - var fromDirectory = Sql.getFromDirectory(from, pathFromClause) - - var list = Manager.instance.getList() - var files_array = list.filter((element, index) => { - if(element.publish) { - if (element.path.indexOf(fromDirectory) > -1) { - return true - } + return pathFromDir +} + +export function executeOrderByClause(files, orderby){ + if(typeof orderby !== 'undefined' && orderby !== null) { + if(orderby.column.toLowerCase() === 'random') { + shuffle(files) + }else if(orderby.column.toLowerCase() === 'date') { + if(orderby.type === 'ASC') { + files.sort(sortByDateAsc) + }else if(orderby.type === 'DESC') { + files.sort(sortByDateDesc) } - return false - }) - return files_array + } } - static execQuery(pathQuery, match, jsonPage) { - var res - var files - var request = Sql.handleSqlRequest(getAttr(match, 'source'), jsonPage) + return files +} - files = Sql.executeFromClause(request.from, pathQuery) - files = Sql.executeOrderByClause(files, request.orderby) - res = Sql.executeWhereClause(files, request.where, request.limit, request.columns, jsonPage) +export function executeFromClause(statement, pathFromClause){ + var from = sanitizeFromStatement(statement) - return res + // if the from clause ends with a dot, we won't recurse the directory analyze + if(from.slice(-1) === '.'){ + from = from.slice(0, -1) + } + + var fromDirectory = getFromDirectory(from, pathFromClause) + + var list = Manager.instance.getList() + var files_array = list.filter((element, index) => { + if(element.publish) { + if (element.path.indexOf(fromDirectory) > -1) { + return true + } + } + return false + }) + return files_array +} + +export function execQuery(pathQuery, match, jsonPage) { + var res + var files + var request = handleSqlRequest(getAttr(match, 'source'), jsonPage) + + files = executeFromClause(request.from, pathQuery) + files = executeOrderByClause(files, request.orderby) + res = executeWhereClause(files, request.where, request.limit, request.columns, jsonPage) + + return res +} + +export function executeQuerySync(pathQuerySync, match, jsonPage) { + return execQuery(pathQuerySync, match, jsonPage) +} + +export function executeQuery(pathexecuteQuery, match, jsonPage) { + var p = new Promise((resolve) => { + var res = execQuery(pathexecuteQuery, match, jsonPage) + resolve(res) + }).catch(function(e) { + console.error(e) + }) + + return p +} + +/** + * check if a given string an url, string json, file url, abe sql request + * + * get('http://google.com') + * get('{"test":"test"}') + * get('select * from ../') + * get('test') + * + * @param {String} str + * @return {String} url | request | value | file | other + */ +export function getSourceType(str) { + if(/http:\/\/|https:\/\//.test(str)) { + return 'url' } - static executeQuerySync(pathQuerySync, match, jsonPage) { - return Sql.execQuery(pathQuerySync, match, jsonPage) + if(/select[\S\s]*?from/.test(str)) { + return 'request' } - static executeQuery(pathexecuteQuery, match, jsonPage) { - var p = new Promise((resolve) => { - var res = Sql.execQuery(pathexecuteQuery, match, jsonPage) - resolve(res) - }).catch(function(e) { - console.error(e) - }) + try { + JSON.parse(str) + return 'value' + }catch(e) { - return p } - /** - * check if a given string an url, string json, file url, abe sql request - * - * Sql.get('http://google.com') - * Sql.get('{"test":"test"}') - * Sql.get('select * from ../') - * Sql.get('test') - * - * @param {String} str - * @return {String} url | request | value | file | other - */ - static getSourceType(str) { - if(/http:\/\/|https:\/\//.test(str)) { - return 'url' - } - - if(/select[\S\s]*?from/.test(str)) { - return 'request' - } + if(/\.json/.test(str)) { + return 'file' + } - try { - JSON.parse(str) - return 'value' - }catch(e) { + return 'other' +} - } +export function executeWhereClause(files, wheres, maxLimit, columns, jsonPage){ + var res = [] + var limit = 0 - if(/\.json/.test(str)) { - return 'file' - } + for(let file of files) { + if(limit < maxLimit || maxLimit === -1) { + if(typeof wheres !== 'undefined' && wheres !== null) { - return 'other' - } + if(!recurseWhere(wheres, file.publish, jsonPage)) { + var json = JSON.parse(JSON.stringify(file.publish)) + var jsonValues = {} - static executeWhereClause(files, wheres, maxLimit, columns, jsonPage){ - var res = [] - var limit = 0 - - for(let file of files) { - if(limit < maxLimit || maxLimit === -1) { - if(typeof wheres !== 'undefined' && wheres !== null) { - - if(!Sql.recurseWhere(wheres, file.publish, jsonPage)) { - var json = JSON.parse(JSON.stringify(file.publish)) - var jsonValues = {} - - if(typeof columns !== 'undefined' && columns !== null && columns.length > 0 && columns[0] !== '*') { - - Array.prototype.forEach.call(columns, (column) => { - if(typeof json[column] !== 'undefined' && json[column] !== null) { - jsonValues[column] = json[column] - } - }) - jsonValues['abe_meta'] = json['abe_meta'] - }else { - jsonValues = json - } - - res.push(jsonValues) - limit++ + if(typeof columns !== 'undefined' && columns !== null && columns.length > 0 && columns[0] !== '*') { + + Array.prototype.forEach.call(columns, (column) => { + if(typeof json[column] !== 'undefined' && json[column] !== null) { + jsonValues[column] = json[column] + } + }) + jsonValues['abe_meta'] = json['abe_meta'] + }else { + jsonValues = json } + + res.push(jsonValues) + limit++ } - } else { - break } + } else { + break } - - return res } - static getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) { - var regexIsVariable = /^{{(.*)}}$/ - var value - var compare + return res +} - try { - var variableLeft = where.left.column - var checkIfLeftIsAVariable = regexIsVariable.exec(variableLeft) - if(typeof checkIfLeftIsAVariable !== 'undefined' && checkIfLeftIsAVariable !== null && checkIfLeftIsAVariable.length > 0) { - variableLeft = checkIfLeftIsAVariable[1] - } - value = eval('jsonDoc.' + variableLeft) - }catch(e) { - // console.log('e', e) - } - - if(where.operator === 'IN' || where.operator === 'NOT IN') { - compare = [] - Array.prototype.forEach.call(where.right.value, (right) => { - var matchRightVariable = regexIsVariable.exec(right.column) - if(typeof matchRightVariable !== 'undefined' && matchRightVariable !== null && matchRightVariable.length > 0) { - try { - var jsonOriginalValues = eval('jsonOriginalDoc.' + matchRightVariable[1]) - Array.prototype.forEach.call(jsonOriginalValues, (jsonOriginalValue) => { - compare.push(eval('jsonOriginalValue.' + where.left.column)) - }) - }catch(e) {} - } - else{ - compare.push(right.column) - } - }) - }else { - compare = where.right.column - var matchRightVariable = regexIsVariable.exec(compare) +export function getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) { + var regexIsVariable = /^{{(.*)}}$/ + var value + var compare + try { + var variableLeft = where.left.column + var checkIfLeftIsAVariable = regexIsVariable.exec(variableLeft) + if(typeof checkIfLeftIsAVariable !== 'undefined' && checkIfLeftIsAVariable !== null && checkIfLeftIsAVariable.length > 0) { + variableLeft = checkIfLeftIsAVariable[1] + } + value = eval('jsonDoc.' + variableLeft) + }catch(e) { + // console.log('e', e) + } + + if(where.operator === 'IN' || where.operator === 'NOT IN') { + compare = [] + Array.prototype.forEach.call(where.right.value, (right) => { + var matchRightVariable = regexIsVariable.exec(right.column) if(typeof matchRightVariable !== 'undefined' && matchRightVariable !== null && matchRightVariable.length > 0) { try { - var shouldCompare = eval('jsonOriginalDoc.' + matchRightVariable[1]) - if(typeof shouldCompare !== 'undefined' && shouldCompare !== null) { - compare = shouldCompare - }else { - compare = null - } - }catch(e) { + var jsonOriginalValues = eval('jsonOriginalDoc.' + matchRightVariable[1]) + Array.prototype.forEach.call(jsonOriginalValues, (jsonOriginalValue) => { + compare.push(eval('jsonOriginalValue.' + where.left.column)) + }) + }catch(e) {} + } + else{ + compare.push(right.column) + } + }) + }else { + compare = where.right.column + var matchRightVariable = regexIsVariable.exec(compare) + + if(typeof matchRightVariable !== 'undefined' && matchRightVariable !== null && matchRightVariable.length > 0) { + try { + var shouldCompare = eval('jsonOriginalDoc.' + matchRightVariable[1]) + if(typeof shouldCompare !== 'undefined' && shouldCompare !== null) { + compare = shouldCompare + }else { compare = null } + }catch(e) { + compare = null } } - - return { - left: value, - right: compare - } } - static recurseWhere(where, jsonDoc, jsonOriginalDoc) { - var shouldAdd = true - var isNotLeftCorrect = false - var isNotRightCorrect = false - var isNotCorrect = false - - switch(where.operator) { - case '=': - var values = Sql.getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) - isNotCorrect = !(values.left === values.right) - break - case '!=': - var values = Sql.getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) - isNotCorrect = !(values.left !== values.right) - break - case '>': - var values = Sql.getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) - isNotCorrect = !(values.left > values.right) - break - case '>=': - var values = Sql.getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) - isNotCorrect = !(values.left >= values.right) - break - case '<': - var values = Sql.getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) - isNotCorrect = !(values.left < values.right) - break - case '<=': - var values = Sql.getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) - isNotCorrect = !(values.left <= values.right) - break - case 'LIKE': - var values = Sql.getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) - isNotCorrect = !(values.left && values.left.indexOf(values.right) > -1) - break - case 'NOT LIKE': - var values = Sql.getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) - isNotCorrect = !(values.left && values.left.indexOf(values.right) === -1) - break - case 'AND': - isNotLeftCorrect = Sql.recurseWhere(where.left, jsonDoc, jsonOriginalDoc) - isNotRightCorrect = Sql.recurseWhere(where.right, jsonDoc, jsonOriginalDoc) - isNotCorrect = (isNotLeftCorrect || isNotRightCorrect) ? true : false - break - case 'OR': - isNotLeftCorrect = Sql.recurseWhere(where.left, jsonDoc, jsonOriginalDoc) - isNotRightCorrect = Sql.recurseWhere(where.right, jsonDoc, jsonOriginalDoc) - isNotCorrect = (isNotLeftCorrect && isNotRightCorrect) ? true : false - break - case 'IN': - var values = Sql.getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) - isNotCorrect = true - Array.prototype.forEach.call(values.right, (right) => { - if(values.left === right) { - isNotCorrect = false - } - }) - break - case 'NOT IN': - var values = Sql.getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) - isNotCorrect = false - Array.prototype.forEach.call(values.right, (right) => { - if(values.left === right) { - isNotCorrect = true - } - }) - break - } - return isNotCorrect + return { + left: value, + right: compare + } +} + +export function recurseWhere(where, jsonDoc, jsonOriginalDoc) { + var shouldAdd = true + var isNotLeftCorrect = false + var isNotRightCorrect = false + var isNotCorrect = false + + switch(where.operator) { + case '=': + var values = getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) + isNotCorrect = !(values.left === values.right) + break + case '!=': + var values = getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) + isNotCorrect = !(values.left !== values.right) + break + case '>': + var values = getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) + isNotCorrect = !(values.left > values.right) + break + case '>=': + var values = getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) + isNotCorrect = !(values.left >= values.right) + break + case '<': + var values = getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) + isNotCorrect = !(values.left < values.right) + break + case '<=': + var values = getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) + isNotCorrect = !(values.left <= values.right) + break + case 'LIKE': + var values = getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) + isNotCorrect = !(values.left && values.left.indexOf(values.right) > -1) + break + case 'NOT LIKE': + var values = getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) + isNotCorrect = !(values.left && values.left.indexOf(values.right) === -1) + break + case 'AND': + isNotLeftCorrect = recurseWhere(where.left, jsonDoc, jsonOriginalDoc) + isNotRightCorrect = recurseWhere(where.right, jsonDoc, jsonOriginalDoc) + isNotCorrect = (isNotLeftCorrect || isNotRightCorrect) ? true : false + break + case 'OR': + isNotLeftCorrect = recurseWhere(where.left, jsonDoc, jsonOriginalDoc) + isNotRightCorrect = recurseWhere(where.right, jsonDoc, jsonOriginalDoc) + isNotCorrect = (isNotLeftCorrect && isNotRightCorrect) ? true : false + break + case 'IN': + var values = getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) + isNotCorrect = true + Array.prototype.forEach.call(values.right, (right) => { + if(values.left === right) { + isNotCorrect = false + } + }) + break + case 'NOT IN': + var values = getWhereValuesToCompare(where, jsonDoc, jsonOriginalDoc) + isNotCorrect = false + Array.prototype.forEach.call(values.right, (right) => { + if(values.left === right) { + isNotCorrect = true + } + }) + break } + return isNotCorrect } \ No newline at end of file diff --git a/src/cli/cms/operations/abe-create.js b/src/cli/cms/operations/abe-create.js index 34854b07..2991642b 100644 --- a/src/cli/cms/operations/abe-create.js +++ b/src/cli/cms/operations/abe-create.js @@ -4,7 +4,7 @@ import { FileParser, Util, cleanSlug, - getTemplate, + cmsTemplate, save, config, Hooks, @@ -27,7 +27,7 @@ var create = function(template, pathCreate, name, req, forceJson = {}, duplicate if(!fileUtils.isFile(tplUrl.json.path)) { var json = (forceJson) ? forceJson : {} var tpl = templatePath - var text = getTemplate(tpl) + var text = cmsTemplate.template.getTemplate(tpl) if (duplicate) { json = cmsData.removeDuplicateAttr(text, json) } diff --git a/src/cli/cms/operations/abe-duplicate.js b/src/cli/cms/operations/abe-duplicate.js index 63aa6a66..cc586f3e 100644 --- a/src/cli/cms/operations/abe-duplicate.js +++ b/src/cli/cms/operations/abe-duplicate.js @@ -7,7 +7,6 @@ import { Util, Manager, cleanSlug, - getTemplate, config, save, abeCreate diff --git a/src/cli/cms/operations/save.js b/src/cli/cms/operations/save.js index 43fac258..3e2c5ace 100755 --- a/src/cli/cms/operations/save.js +++ b/src/cli/cms/operations/save.js @@ -15,7 +15,7 @@ import { ,fileAttr ,dateSlug ,Page - ,getTemplate + ,cmsTemplate ,Hooks ,cleanSlug } from '../../' @@ -112,7 +112,7 @@ export function save(url, tplPath, json = null, text = '', type = '', previousSa Util.addMetas(tpl, json, type, {}, date, realType) if(typeof text === 'undefined' || text === null || text === '') { - text = getTemplate(fullTpl) + text = cmsTemplate.template.getTemplate(fullTpl) } Util.getDataList(fileUtils.removeLast(tplUrl.publish.link), text, json) diff --git a/src/cli/cms/templates/abe-get-select-template-keys.js b/src/cli/cms/templates/abe-get-select-template-keys.js deleted file mode 100644 index f218293f..00000000 --- a/src/cli/cms/templates/abe-get-select-template-keys.js +++ /dev/null @@ -1,170 +0,0 @@ -import path from 'path' -import fse from 'fs-extra' -import {execFile} from 'child_process' -import { - fileUtils, - FileParser, - Util, - cmsData, - cleanSlug, - getTemplate, - save, - config, - Hooks, - Manager -} from '../../' - -var traverseFileSystem = function (currentPath, arr) { - var res = [] - var files = fse.readdirSync(currentPath) - for (var i in files) { - var currentFile = currentPath + '/' + files[i] - var stats = fse.statSync(currentFile) - if (stats.isFile()) { - if (currentFile.indexOf(config.files.templates.extension) > -1) { - res.push(currentFile) - } - } - else if (stats.isDirectory()) { - res = res.concat(traverseFileSystem(currentFile)) - } - } - return res -} - -var findTemplates = function(templatesPath) { - var p = new Promise((resolve, reject) => { - let templatesList = traverseFileSystem(templatesPath) - resolve(templatesList) - }) - - return p -} - -/** - * Get columns and where.left ids of a select statement - * - * select title, image from ../ where template="" - * - * return [title, image, template] - * - * @param {Array} templatesList ["article.html", "other.html"] - * @return {Promise} - */ - -var recurseWhereVariables = function (where) { - var ar = [] - switch(where.operator) { - case 'AND': - var arLeft = recurseWhereVariables(where.left) - var arRight = recurseWhereVariables(where.right) - return arLeft.concat(arRight) - break - case 'OR': - var arLeft = recurseWhereVariables(where.left) - var arRight = recurseWhereVariables(where.right) - return arLeft.concat(arRight) - break - case 'IN': - break - case 'NOT IN': - if(where.left.column.indexOf('{{') > -1) { - ar.push(where.left.column.replace(/\{\{(.*?)\}\}/, '$1')) - } - else{ - ar.push(where.left.column) - } - - where.right.value.forEach(function (value) { - if(value.column.indexOf('{{') > -1) { - ar.push(value.column.replace(/\{\{(.*?)\}\}/, '$1')) - } - }) - - break - default: - if(where.left.column.indexOf('{{') > -1) { - ar.push(where.left.column.replace(/\{\{(.*?)\}\}/, '$1')) - } - else{ - ar.push(where.left.column) - } - if(where.right.value && where.right.value.indexOf('{{') > -1) { - ar.push(where.right.value.replace(/\{\{(.*?)\}\}/, '$1')) - } - if(where.right.column && where.right.column.indexOf('{{') > -1) { - ar.push(where.right.column.replace(/\{\{(.*?)\}\}/, '$1')) - } - break - } - - return ar -} - -var findRequestColumns = function(templatesList) { - var whereKeysCheck = {} - var whereKeys = [] - var p = new Promise((resolve, reject) => { - let util = new Util() - Array.prototype.forEach.call(templatesList, (file) => { - var template = fse.readFileSync(file, 'utf8') - var matches = util.dataRequest(template) - - Array.prototype.forEach.call(matches, (match) => { - var obj = Util.getAllAttributes(match[0], {}) - var type = Sql.getSourceType(obj.sourceString) - - switch (type) { - case 'request': - var request = cmsData.sql.handleSqlRequest(obj.sourceString, {}) - if(typeof request.columns !== 'undefined' && request.columns !== null) { - Array.prototype.forEach.call(request.columns, (column) => { - whereKeys.push(column) - }) - } - if(typeof request.where !== 'undefined' && request.where !== null) { - whereKeys = whereKeys.concat(recurseWhereVariables(request.where)) - } - } - }) - }) - whereKeys = whereKeys.filter(function (item, pos) {return whereKeys.indexOf(item) == pos}) - resolve(whereKeys) - }) - - return p -} - -var getSelectTemplateKeys = function(templatesPath) { - var p = new Promise((resolve, reject) => { - findTemplates(templatesPath) - .then((templatesList) => { - - findRequestColumns(templatesList) - .then((whereKeys) => { - resolve(whereKeys) - }, - () => { - console.log('findRequestColumns reject') - reject() - }) - .catch((e) => { - console.error('getSelectTemplateKeys', e) - reject() - }) - }, - () => { - console.log('findTemplates reject') - reject() - }) - .catch((e) => { - console.error('getSelectTemplateKeys', e) - reject() - }) - - }) - - return p -} - -export default getSelectTemplateKeys \ No newline at end of file diff --git a/src/cli/cms/templates/abe-template.js b/src/cli/cms/templates/abe-template.js deleted file mode 100755 index c8ecbf1b..00000000 --- a/src/cli/cms/templates/abe-template.js +++ /dev/null @@ -1,138 +0,0 @@ -import fse from 'fs-extra' -import extend from 'extend' -import {Promise} from 'es6-promise' -import path from 'path' -import { - getAttr - ,Util - ,config - ,fileUtils - ,FileParser - ,escapeTextToRegex - ,Hooks - ,Plugins -} from '../../' - -export function addOrder(text) { - var regAbe = /{{abe[\S\s].*?key=['|"]([\S\s].*?['|"| ]}})/g - var matches = text.match(regAbe) - var order = 0 - - if(typeof matches !== 'undefined' && matches !== null){ - Array.prototype.forEach.call(matches, (match) => { - if(typeof match !== 'undefined' && match !== null) { - - var keyAttr = getAttr(match, 'key') - var orderAttr = getAttr(match, 'order') - - if(typeof orderAttr === 'undefined' || orderAttr === null || orderAttr === '') { - var matchOrder = match.replace(/\}\}$/, ` order='${order}'}}`) - text = text.replace(match, matchOrder) - } - order++ - } - }) - } - return text -} - -export function getAbeImport(text) { - var partials = [] - let listReg = /({{abe.*?type=[\'|\"]import.*?}})/g - var match - while (match = listReg.exec(text)) { - partials.push(match[0]) - } - - return partials -} - -export function includePartials(text) { - var abeImports = getAbeImport(text) - - Array.prototype.forEach.call(abeImports, (abeImport) => { - var obj = Util.getAllAttributes(abeImport, {}) - - var file = obj.file - var partial = '' - file = path.join(config.root, config.partials, file) - if(fileUtils.isFile(file)) { - partial = includePartials(fse.readFileSync(file, 'utf8')) - } - text = text.replace(escapeTextToRegex(abeImport, 'g'), partial) - }) - - return text -} - -function translate(text) { - var importReg = /({{abe.*type=[\'|\"]translate.*}})/g - var match - - - var matches = text.match(importReg) - var order = 0 - - if(typeof matches !== 'undefined' && matches !== null) { - Array.prototype.forEach.call(matches, (match) => { - var splitedMatches = match.split('{{abe ') - - Array.prototype.forEach.call(splitedMatches, (splitedMatch) => { - var currentMatch = `{{abe ${splitedMatch}` - if(/({{abe.*type=[\'|\"]translate.*}})/.test(currentMatch)) { - var locale = getAttr(currentMatch, 'locale') - var source = getAttr(currentMatch, 'source') - - if (locale.indexOf('{{') === -1) { - locale = `'${locale}'` - }else { - locale = locale.replace(/\{\{(.*?)\}\}/, '$1') - } - - if (source.indexOf('{{') === -1) { - source = `'${source.replace(/'/g, '\\\'')}'` - }else { - source = source.replace(/\{\{(.*?)\}\}/, '$1') - } - - // var replace = `{{{i18nAbe ${locale} ${source}}}}` - var replace = currentMatch.replace('{{abe', '{{i18nAbe') - replace = replace.replace(/locale=['|"].*?['|"]/, locale) - replace = replace.replace(/source=['|"].*?['|"]/, source) - replace = replace.replace(/{{i18nAbe.*?}}/, `{{{i18nAbe ${locale} ${source}}}}`) - - text = text.replace(escapeTextToRegex(currentMatch, 'g'), replace) - } - }) - }) - } - - return text -} - -export function getTemplate (file) { - var text = '' - - // HOOKS beforeGetTemplate - file = Hooks.instance.trigger('beforeGetTemplate', file) - - file = file.replace(path.join(config.root, config.templates.url), '') - file = file.replace(config.root, '') - if (file.indexOf('.') > -1) { - file = fileUtils.removeExtension(file) - } - file = path.join(config.root, config.templates.url, file + '.' + config.files.templates.extension) - if(fileUtils.isFile(file)) { - text = fse.readFileSync(file, 'utf8') - text = includePartials(text) - text = translate(text) - text = addOrder(text) - }else { - text = `[ ERROR ] template ${config.templates.url} doesn't exist anymore` - } - - // HOOKS afterGetTemplate - text = Hooks.instance.trigger('afterGetTemplate', text) - - return text -} \ No newline at end of file diff --git a/src/cli/cms/templates/index.js b/src/cli/cms/templates/index.js index 2cf73a52..3c126d76 100755 --- a/src/cli/cms/templates/index.js +++ b/src/cli/cms/templates/index.js @@ -19,6 +19,8 @@ import translate from './handlebars/translate' import times from './handlebars/times' import truncate from './handlebars/truncate' +import * as template from './template' + /* Register utilities */ Handlebars.registerHelper('attrAbe', attrAbe) Handlebars.registerHelper('className', className) @@ -38,6 +40,7 @@ Handlebars.registerHelper('truncate', truncate) HandlebarsIntl.registerWith(Handlebars) export { + template, attrAbe, className, cleanTab, diff --git a/src/cli/cms/templates/template.js b/src/cli/cms/templates/template.js new file mode 100755 index 00000000..220f926a --- /dev/null +++ b/src/cli/cms/templates/template.js @@ -0,0 +1,292 @@ +import fse from 'fs-extra' +import {Promise} from 'es6-promise' +import path from 'path' +import { + getAttr + ,Util + ,config + ,fileUtils + ,cmsData + ,escapeTextToRegex + ,Hooks +} from '../../' + +export function findTemplateAndPartialsInFolder (currentPath) { + var res = [] + var files = fse.readdirSync(currentPath) + for (var i in files) { + var currentFile = currentPath + '/' + files[i] + var stats = fse.statSync(currentFile) + if (stats.isFile()) { + if (currentFile.indexOf('.' + config.files.templates.extension) > -1) { + res.push(currentFile) + } + } + else if (stats.isDirectory()) { + res = res.concat(findTemplateAndPartialsInFolder(currentFile)) + } + } + return res +} + +export function getTemplateAndPartials(templatesPath) { + var p = new Promise((resolve) => { + let templatesList = findTemplateAndPartialsInFolder(templatesPath) + resolve(templatesList) + }) + + return p +} + +export function addOrder(text) { + var regAbe = /{{abe[\S\s].*?key=['|"]([\S\s].*?['|"| ]}})/g + var matches = text.match(regAbe) + var order = 0 + + if(typeof matches !== 'undefined' && matches !== null){ + Array.prototype.forEach.call(matches, (match) => { + if(typeof match !== 'undefined' && match !== null) { + + var orderAttr = getAttr(match, 'order') + + if(typeof orderAttr === 'undefined' || orderAttr === null || orderAttr === '') { + var matchOrder = match.replace(/\}\}$/, ` order='${order}'}}`) + text = text.replace(match, matchOrder) + } + order++ + } + }) + } + return text +} + +export function getAbeImport(text) { + var partials = [] + let listReg = /({{abe.*?type=[\'|\"]import.*?}})/g + var match + while (match = listReg.exec(text)) { + partials.push(match[0]) + } + + return partials +} + +export function includePartials(text) { + var abeImports = getAbeImport(text) + + Array.prototype.forEach.call(abeImports, (abeImport) => { + var obj = Util.getAllAttributes(abeImport, {}) + + var file = obj.file + var partial = '' + file = path.join(config.root, config.partials, file) + if(fileUtils.isFile(file)) { + partial = includePartials(fse.readFileSync(file, 'utf8')) + } + text = text.replace(escapeTextToRegex(abeImport, 'g'), partial) + }) + + return text +} + +function translate(text) { + var importReg = /({{abe.*type=[\'|\"]translate.*}})/g + + var matches = text.match(importReg) + + if(typeof matches !== 'undefined' && matches !== null) { + Array.prototype.forEach.call(matches, (match) => { + var splitedMatches = match.split('{{abe ') + + Array.prototype.forEach.call(splitedMatches, (splitedMatch) => { + var currentMatch = `{{abe ${splitedMatch}` + if(/({{abe.*type=[\'|\"]translate.*}})/.test(currentMatch)) { + var locale = getAttr(currentMatch, 'locale') + var source = getAttr(currentMatch, 'source') + + if (locale.indexOf('{{') === -1) { + locale = `'${locale}'` + }else { + locale = locale.replace(/\{\{(.*?)\}\}/, '$1') + } + + if (source.indexOf('{{') === -1) { + source = `'${source.replace(/'/g, '\\\'')}'` + }else { + source = source.replace(/\{\{(.*?)\}\}/, '$1') + } + + // var replace = `{{{i18nAbe ${locale} ${source}}}}` + var replace = currentMatch.replace('{{abe', '{{i18nAbe') + replace = replace.replace(/locale=['|"].*?['|"]/, locale) + replace = replace.replace(/source=['|"].*?['|"]/, source) + replace = replace.replace(/{{i18nAbe.*?}}/, `{{{i18nAbe ${locale} ${source}}}}`) + + text = text.replace(escapeTextToRegex(currentMatch, 'g'), replace) + } + }) + }) + } + + return text +} + +export function getTemplate (file) { + var text = '' + + // HOOKS beforeGetTemplate + file = Hooks.instance.trigger('beforeGetTemplate', file) + + file = file.replace(path.join(config.root, config.templates.url), '') + file = file.replace(config.root, '') + if (file.indexOf('.') > -1) { + file = fileUtils.removeExtension(file) + } + file = path.join(config.root, config.templates.url, file + '.' + config.files.templates.extension) + if(fileUtils.isFile(file)) { + text = fse.readFileSync(file, 'utf8') + text = includePartials(text) + text = translate(text) + text = addOrder(text) + }else { + text = `[ ERROR ] template ${config.templates.url} doesn't exist anymore` + } + + // HOOKS afterGetTemplate + text = Hooks.instance.trigger('afterGetTemplate', text) + + return text +} + +export function getVariablesInWhere(where) { + var ar = [] + + if(where.left.column.indexOf('{{') > -1) { + ar.push(where.left.column.replace(/\{\{(.*?)\}\}/, '$1')) + } + else{ + ar.push(where.left.column) + } + + if (where.right.value) { + if (typeof where.right.value === 'string') { + if(where.right.value && where.right.value.indexOf('{{') > -1) { + ar.push(where.right.value.replace(/\{\{(.*?)\}\}/, '$1')) + } + }else { + where.right.value.forEach(function (value) { + if(value.column.indexOf('{{') > -1) { + ar.push(value.column.replace(/\{\{(.*?)\}\}/, '$1')) + } + }) + } + } + + if(where.right.column && where.right.column.indexOf('{{') > -1) { + ar.push(where.right.column.replace(/\{\{(.*?)\}\}/, '$1')) + } + + return ar +} + +/** + * Get columns and where.left ids of a select statement + * + * select title, image from ../ where template="" + * + * return [title, image, template] + * + * @param {Array} templatesList ["article.html", "other.html"] + * @return {Promise} + */ +export function recurseWhereVariables (where) { + var ar = [] + var arLeft + var arRight + switch(where.operator) { + case 'AND': + arLeft = recurseWhereVariables(where.left) + arRight = recurseWhereVariables(where.right) + return arLeft.concat(arRight) + break + case 'OR': + arLeft = recurseWhereVariables(where.left) + arRight = recurseWhereVariables(where.right) + return arLeft.concat(arRight) + break + default: + ar = getVariablesInWhere(where) + break + } + + return ar +} + +export function execRequestColumns(tpl) { + let util = new Util() + var ar = [] + var matches = util.dataRequest(tpl) + Array.prototype.forEach.call(matches, (match) => { + var obj = Util.getAllAttributes(match[0], {}) + var type = cmsData.sql.getSourceType(obj.sourceString) + switch (type) { + case 'request': + var request = cmsData.sql.handleSqlRequest(obj.sourceString, {}) + if(typeof request.columns !== 'undefined' && request.columns !== null) { + Array.prototype.forEach.call(request.columns, (column) => { + ar.push(column) + }) + } + if(typeof request.where !== 'undefined' && request.where !== null) { + ar = ar.concat(recurseWhereVariables(request.where)) + } + } + }) + + return ar +} + +export function findRequestColumns(templatesList) { + var whereKeys = [] + var p = new Promise((resolve) => { + Array.prototype.forEach.call(templatesList, (file) => { + var template = fse.readFileSync(file, 'utf8') + whereKeys = whereKeys.concat(execRequestColumns(template)) + }) + whereKeys = whereKeys.filter(function (item, pos) {return whereKeys.indexOf(item) == pos}) + resolve(whereKeys) + }) + + return p +} + +export function getSelectTemplateKeys(templatesPath) { + var p = new Promise((resolve, reject) => { + getTemplateAndPartials(templatesPath) + .then((templatesList) => { + findRequestColumns(templatesList) + .then((whereKeys) => { + resolve(whereKeys) + }, + () => { + console.log('findRequestColumns reject') + reject() + }) + .catch((e) => { + console.error('getSelectTemplateKeys', e) + reject() + }) + }, + () => { + console.log('getTemplateAndPartials reject') + reject() + }) + .catch((e) => { + console.error('getSelectTemplateKeys', e) + reject() + }) + + }) + + return p +} \ No newline at end of file diff --git a/src/cli/core/manager/Manager.js b/src/cli/core/manager/Manager.js index fb1b39cb..f75279f6 100644 --- a/src/cli/core/manager/Manager.js +++ b/src/cli/core/manager/Manager.js @@ -6,7 +6,7 @@ import { config, FileParser, folderUtils, - getSelectTemplateKeys + cmsTemplate } from '../../' let singleton = Symbol() @@ -44,7 +44,7 @@ class Manager { this._whereKeys = [] var p = new Promise((resolve) => { const pathTemplate = path.join(config.root, config.templates.url) - getSelectTemplateKeys(pathTemplate) + cmsTemplate.template.getSelectTemplateKeys(pathTemplate) .then((whereKeys) => { this._whereKeys = whereKeys this.updateList() diff --git a/src/cli/index.js b/src/cli/index.js index 1c9715f8..5d839a81 100755 --- a/src/cli/index.js +++ b/src/cli/index.js @@ -44,7 +44,7 @@ import folderUtils from './core/utils/folder-utils' import slugify from './core/utils/slugify' import {cleanSlug} from './core/utils/slugify' -import {getTemplate} from './cms/templates/abe-template' +// import {getTemplate} from './cms/templates/abe-template' import Create from './cms/Create' import config from './core/config/config' @@ -59,12 +59,12 @@ import abeProcess from './extend/abe-process' import Hooks from './extend/abe-hooks' import Plugins from './extend/abe-plugins' -import getSelectTemplateKeys from './cms/templates/abe-get-select-template-keys' - import * as cmsData from './cms/data' +import * as cmsTemplate from './cms/templates' export { cmsData + ,cmsTemplate ,fileAttr ,moment @@ -102,7 +102,6 @@ export { ,getEnclosingTags ,escapeTextToRegex ,config - ,getTemplate ,save ,Hooks ,Plugins @@ -113,7 +112,6 @@ export { ,dateUnslug ,Manager ,Page - ,getSelectTemplateKeys } export {compileAbe as compileAbe} diff --git a/src/server/controllers/editor.js b/src/server/controllers/editor.js index 97309781..c68ecaca 100755 --- a/src/server/controllers/editor.js +++ b/src/server/controllers/editor.js @@ -4,7 +4,7 @@ import { Util, fileUtils, abeEngine, - getTemplate, + cmsTemplate, FileParser, Hooks } from '../../cli' @@ -226,7 +226,7 @@ export function editor(fileName, jsonPath, documentLink) { json = FileParser.getJson(jsonPath, 'utf8') } - text = getTemplate(fileName) + text = cmsTemplate.template.getTemplate(fileName) Util.getDataList(fileUtils.removeLast(documentLink), text, json, true) .then(() => { diff --git a/src/server/controllers/index.js b/src/server/controllers/index.js index bd9ad731..b3ae4946 100755 --- a/src/server/controllers/index.js +++ b/src/server/controllers/index.js @@ -42,7 +42,6 @@ import { Page, Locales, abeProcess, - getTemplate, Hooks, Plugins, Handlebars, diff --git a/src/server/helpers/page.js b/src/server/helpers/page.js index dd9a1931..19f855b5 100644 --- a/src/server/helpers/page.js +++ b/src/server/helpers/page.js @@ -6,7 +6,7 @@ import { fileUtils, config, Page, - getTemplate, + cmsTemplate, cleanSlug } from '../../cli' @@ -54,7 +54,7 @@ var page = function (req, res, next) { }else { template = req.params[0] } - var text = getTemplate(template) + var text = cmsTemplate.template.getTemplate(template) if (!editor) { diff --git a/src/server/middlewares/website.js b/src/server/middlewares/website.js index 6036aefb..af2b5e3f 100644 --- a/src/server/middlewares/website.js +++ b/src/server/middlewares/website.js @@ -21,7 +21,6 @@ import { Page, Locales, abeProcess, - getTemplate, Hooks, Plugins, Handlebars, diff --git a/src/server/routes/get-create.js b/src/server/routes/get-create.js index c8ab2baf..c46754dd 100644 --- a/src/server/routes/get-create.js +++ b/src/server/routes/get-create.js @@ -3,7 +3,6 @@ import { FileParser, Util, cleanSlug, - getTemplate, config, save, abeCreate, diff --git a/src/server/routes/get-list-hooks.js b/src/server/routes/get-list-hooks.js index c1749d7f..a6202a6b 100644 --- a/src/server/routes/get-list-hooks.js +++ b/src/server/routes/get-list-hooks.js @@ -6,7 +6,6 @@ import { FileParser, Util, cleanSlug, - getTemplate, config, save, abeCreate, diff --git a/src/server/routes/get-list-url.js b/src/server/routes/get-list-url.js index 92b43679..20811d12 100644 --- a/src/server/routes/get-list-url.js +++ b/src/server/routes/get-list-url.js @@ -5,7 +5,6 @@ import { FileParser, Util, cleanSlug, - getTemplate, config, save, abeCreate, diff --git a/src/server/routes/get-main.js b/src/server/routes/get-main.js index 4090e9b9..fc8bd834 100644 --- a/src/server/routes/get-main.js +++ b/src/server/routes/get-main.js @@ -7,8 +7,8 @@ import { fileUtils, config, Page, + cmsTemplate, Locales, - getTemplate, Hooks, Manager } from '../../cli' @@ -128,7 +128,7 @@ var route = function(req, res, next) { var pageHtml = '' if(typeof _json !== 'undefined' && _json !== null && typeof _json.abe_meta !== 'undefined' && _json.abe_meta !== null) { - var text = getTemplate(_json.abe_meta.template) + var text = cmsTemplate.template.getTemplate(_json.abe_meta.template) var page = new Page(_json.abe_meta.template, text, _json, false) pageHtml = page.html.replace(/"/g, '"').replace(/'/g, '\'').replace(//g, '--ABE>') } diff --git a/test/fixtures/templates/article-keys.html b/test/fixtures/templates/article-keys.html new file mode 100644 index 00000000..d14e54ff --- /dev/null +++ b/test/fixtures/templates/article-keys.html @@ -0,0 +1,3 @@ +{{abe type='data' key='title' desc='select title' source='select title,abe_meta from ./' editable='false'}} +{{abe type='data' key='title2' desc='select title' source='select title,abe_meta from ./ where `abe_meta.template` NOT IN (`homepage`,`test`)' editable='false'}} +{{abe type='data' key='title2' desc='select title' source='select title,abe_meta from ./ where `abe_meta.template` NOT IN (`{{abe_meta.date}}`)' editable='false'}} \ No newline at end of file diff --git a/test/request.js b/test/request.js index c8b562c0..8af8fb73 100644 --- a/test/request.js +++ b/test/request.js @@ -28,7 +28,7 @@ describe('Request', function() { }); /** - * cmsData.sql.getAllAttributes + * Util.getAllAttributes * */ it('Util.getAllAttributes()', function(done) { diff --git a/test/template.js b/test/template.js index 6f9e5455..28df9dfe 100644 --- a/test/template.js +++ b/test/template.js @@ -1,11 +1,10 @@ var chai = require('chai'); +var path = require('path'); var config = require('../src/cli').config config.set({root: __dirname + '/fixtures'}) -var getTemplate = require('../src/cli').getTemplate -var includePartials = require('../src/cli/cms/templates/abe-template').includePartials -var getAbeImport = require('../src/cli/cms/templates/abe-template').getAbeImport +var cmsTemplate = require('../src/cli').cmsTemplate; var Manager = require('../src/cli').Manager; var fse = require('fs-extra'); @@ -14,7 +13,8 @@ describe('Template', function() { Manager.instance.init() .then(function () { this.fixture = { - template: fse.readFileSync(__dirname + '/fixtures/templates/article.html', 'utf-8') + template: fse.readFileSync(__dirname + '/fixtures/templates/article.html', 'utf-8'), + templateKeys: fse.readFileSync(__dirname + '/fixtures/templates/article-keys.html', 'utf-8') } done() @@ -25,8 +25,8 @@ describe('Template', function() { * getAbeImport * */ - it('getAbeImport()', function() { - var res = getAbeImport(this.fixture.template) + it('cmsTemplate.template.getAbeImport()', function() { + var res = cmsTemplate.template.getAbeImport(this.fixture.template) chai.expect(res).to.have.length(4); }); @@ -34,17 +34,39 @@ describe('Template', function() { * includePartials * */ - it('includePartials()', function() { - var template = includePartials(this.fixture.template) + it('cmsTemplate.template.includePartials()', function() { + var template = cmsTemplate.template.includePartials(this.fixture.template) chai.expect(template).to.contain("{{abe type='text' key='title' desc='titre' tab='default'}}"); }); /** - * getTemplate + * cmsTemplate.template.getTemplate * */ - it('getTemplate()', function() { - var template = getTemplate('article') + it('cmsTemplate.template.getTemplate()', function() { + var template = cmsTemplate.template.getTemplate('article') chai.expect(template).to.contain("{{abe type='text' key='title' desc='titre' tab='default' order='1'}}"); }); + + /** + * getTemplate + * + */ + it('cmsTemplate.template.getSelectTemplateKeys()', function() { + const pathTemplate = path.join(config.root, config.templates.url) + cmsTemplate.template.getSelectTemplateKeys(pathTemplate) + .then((whereKeys) => { + chai.expect(whereKeys.indexOf('abe_meta.date')).to.be.above(-1); + }) + }); + + /** + * getTemplate + * + */ + it('cmsTemplate.template.execRequestColumns()', function() { // templateKeys + const pathTemplate = path.join(config.root, config.templates.url) + var ar = cmsTemplate.template.execRequestColumns(this.fixture.templateKeys) + chai.expect(ar.indexOf('abe_meta.date')).to.be.above(-1); + }); });