Skip to content

Instantly share code, notes, and snippets.

@stiekel
Created December 21, 2018 07:05
Show Gist options
  • Save stiekel/f80b5e00fbdbe2c997690061dd6e5430 to your computer and use it in GitHub Desktop.
Save stiekel/f80b5e00fbdbe2c997690061dd6e5430 to your computer and use it in GitHub Desktop.
function parseAttrs (str) {
str = str.replace('(', '')
str = str.replace(')', '')
let parts = str.split(':')
let tmp = {}
if (parts[0] && parts[1]) {
let v = parts[1].trim()
v = v.replace(/\'/g, '')
if (!isNaN(v)) {
v = parseFloat(v)
}
tmp[parts[0].trim()] = v
}
return tmp
}
function parsePart (str) {
str = str.replace('{', '')
str = str.replace('}', '')
}
function parse(str) {
str = str.replace(/[\r\n]/g, '')
str = str.trim()
let result = {}
let fieldsStart = str.indexOf('{')
let fieldsEnd = str.lastIndexOf('}')
let nameAttrs = str.substr(0, fieldsStart)
nameAttrs = nameAttrs.trim()
if (nameAttrs[nameAttrs.length - 1] === ':') {
nameAttrs = nameAttrs.substr(0, nameAttrs.length - 1)
}
// 是否有 attrs
let attrStart = nameAttrs.indexOf('(')
if (attrStart !== -1) {
result.attrs = {
data: parseAttrs(nameAttrs.substr(attrStart))
}
nameAttrs = nameAttrs.substr(0, attrStart)
result.type = nameAttrs
// 检查条件
let subPart = str.substr(attrStart)
subPart = subPart.trim()
if (subPart[0] === '(') {
let attrsPart = subPart.substr(0, subPart.indexOf(')') + 1)
attrsPart = attrsPart.trim()
result.attrs = {
data: parseAttrs(attrsPart)
}
subPart = subPart.substr(subPart.indexOf(')') + 1)
}
subPart = subPart.trim()
if (subPart[0] === ':') {
subPart = subPart.substr(1)
}
subPart = subPart.trim()
subPart = subPart.substr(1, subPart.length - 2)
// 检查字段
let relationStart = subPart.indexOf('{')
if (relationStart === -1) {
result.fields = subPart.split(',')
} else {
// 检查子查询
relationStart = subPart.lastIndexOf(',', relationStart)
// console.log('subPart.substr(0, relationStart)', subPart, '---', subPart.substr(0, relationStart))
result.fields = subPart.substr(0, relationStart).split(',')
let relationPart = subPart.substr(relationStart + 1)
relationPart = relationPart.trim()
let relationName = ''
if (relationPart.indexOf(' ') < relationPart.indexOf('(')) {
relationName = relationPart.substr(0, relationPart.indexOf(' '))
relationPart = relationPart.substr(relationPart.indexOf(' '))
} else {
relationName = relationPart.substr(0, relationPart.indexOf('('))
}
if (relationName) {
if (!result.relations) {
result.relations = {}
}
result.relations[relationName] = {
name: relationName,
target: parse(relationPart)
}
}
}
}
if (result.fields && result.fields.length) {
result.fields = result.fields.map(f => f.trim())
}
return result
}
const inputStr = `User( age:21 ){
id,
name,
assigned Task( content: 'run' ): {
id,
content
}
}`
// console.log(parseAttrs('( s : 1 )'))
console.log(JSON.stringify(parse(inputStr)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment