Skip to content

Commit

Permalink
fix: ensure data access with valid identifier
Browse files Browse the repository at this point in the history
  • Loading branch information
harttle committed Jan 10, 2020
1 parent f058dff commit 8284ddb
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 17 deletions.
27 changes: 10 additions & 17 deletions src/target-js/compilers/expr-compiler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Expression } from '../../models/expression'
import { isString } from 'lodash'
import { isValidIdentifier } from '../../utils/lang'

/**
* 编译源码的 helper 方法集合对象
Expand All @@ -21,25 +23,16 @@ export const compileExprSource = {
*/
dataAccess: function (accessorExpr?: Expression): string {
let code = 'componentCtx.data'
if (accessorExpr) {
for (const path of accessorExpr.paths) {
if (path.type === 4) {
code += '[' + compileExprSource.dataAccess(path) + ']'
continue
}

switch (typeof path.value) {
case 'string':
code += '.' + path.value
continue

case 'number':
code += '[' + path.value + ']'
continue
}
if (!accessorExpr) return code
for (const path of accessorExpr.paths) {
if (path.type === 4) {
code += '[' + compileExprSource.dataAccess(path) + ']'
} else if (isString(path.value) && isValidIdentifier(path.value)) {
code += '.' + path.value
} else {
code += '[' + path.value + ']'
}
}

return code
},

Expand Down
3 changes: 3 additions & 0 deletions src/utils/lang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function isValidIdentifier (str: string) {
return !!/^[a-zA-Z_$][\w$]*$/.exec(str)
}
6 changes: 6 additions & 0 deletions test/cases/data-access/component.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const { Component } = require('san')

class MyComponent extends Component {}

MyComponent.template = '<div>{{staff[0].first}} {{staff.0.last}}</div>'
module.exports = exports = MyComponent
6 changes: 6 additions & 0 deletions test/cases/data-access/data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"staff": [{
"first": "Berg",
"last": "Lay"
}]
}
1 change: 1 addition & 0 deletions test/cases/data-access/expected.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<div><!--s-data:{"staff":[{"first":"Berg","last":"Lay"}]}-->Berg Lay</div>

0 comments on commit 8284ddb

Please sign in to comment.