Skip to content

Commit c801353

Browse files
committed
fix: getValueByKeyPath 追加 fallback 逻辑
1 parent c4d7cba commit c801353

File tree

2 files changed

+34
-23
lines changed

2 files changed

+34
-23
lines changed

src/mock/handler.js

+27-23
Original file line numberDiff line numberDiff line change
@@ -489,29 +489,33 @@ Handler.extend({
489489
}
490490
}
491491

492-
key = keyPathParts[keyPathParts.length - 1]
493-
var currentContext = options.context.root
494-
var templateCurrentContext = options.context.templateRoot
495-
for (var i = 1; i < absolutePathParts.length - 1; i++) {
496-
currentContext = currentContext[absolutePathParts[i]]
497-
templateCurrentContext = templateCurrentContext[absolutePathParts[i]]
498-
}
499-
// 引用的值已经计算好
500-
if (currentContext && (key in currentContext)) return currentContext[key]
501-
502-
// 尚未计算,递归引用数据模板中的属性
503-
if (templateCurrentContext &&
504-
(typeof templateCurrentContext === 'object') &&
505-
(key in templateCurrentContext) &&
506-
(originalKey !== templateCurrentContext[key]) // fix #15 避免自己依赖自己
507-
) {
508-
// 先计算被引用的属性值
509-
templateCurrentContext[key] = Handler.gen(templateCurrentContext[key], key, {
510-
currentContext: currentContext,
511-
templateCurrentContext: templateCurrentContext
512-
})
513-
return templateCurrentContext[key]
514-
}
492+
try {
493+
key = keyPathParts[keyPathParts.length - 1]
494+
var currentContext = options.context.root
495+
var templateCurrentContext = options.context.templateRoot
496+
for (var i = 1; i < absolutePathParts.length - 1; i++) {
497+
currentContext = currentContext[absolutePathParts[i]]
498+
templateCurrentContext = templateCurrentContext[absolutePathParts[i]]
499+
}
500+
// 引用的值已经计算好
501+
if (currentContext && (key in currentContext)) return currentContext[key]
502+
503+
// 尚未计算,递归引用数据模板中的属性
504+
if (templateCurrentContext &&
505+
(typeof templateCurrentContext === 'object') &&
506+
(key in templateCurrentContext) &&
507+
(originalKey !== templateCurrentContext[key]) // fix #15 避免自己依赖自己
508+
) {
509+
// 先计算被引用的属性值
510+
templateCurrentContext[key] = Handler.gen(templateCurrentContext[key], key, {
511+
currentContext: currentContext,
512+
templateCurrentContext: templateCurrentContext
513+
})
514+
return templateCurrentContext[key]
515+
}
516+
} catch(err) { }
517+
518+
return '@' + keyPathParts.join('/')
515519
},
516520
// https://github.com/kissyteam/kissy/blob/master/src/path/src/path.js
517521
normalizePath: function(pathParts) {

test/test.mock.spec.dpd.js

+7
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,13 @@ describe('DPD', function() {
8989
expect(data.child).to.have.property('parentId', data.id)
9090
})
9191

92+
it('Relative Path Fallback in Corner Case', function() {
93+
const STRING = 'https://test.org/@a/build/test.html'
94+
var data = Mock.mock({
95+
a: STRING
96+
})
97+
expect(data.a).to.equal(STRING)
98+
})
9299
})
93100
describe('Complex', function() {
94101
var tpl = {

0 commit comments

Comments
 (0)