Mockoon模板解析错误排查:带过滤功能Mock API实现问题
Mockoon过滤Mock API模板报错问题解决
问题描述
我正在使用Mockoon创建支持过滤功能的Mock API,端点为 localhost:3004/api/v1/users1?filterBy=lastName&value=Brown。
使用的数据桶内容如下:
{ "users":[ { "id": 1, "firstName": "Alice", "lastName": "Smith", "email": "alice@email.com", "username": "aliceUser", "createdAt": "2023-10-02T12:00:00.000Z", "phoneNumbers": [ "123-456-7890", "234-567-8901" ] }, { "id": 2, "firstName": "Bob", "lastName": "Brown", "email": "bob@email.com", "username": "bobUser", "createdAt": "2023-11-01T12:00:00.000Z", "phoneNumbers": ["234-567-8901"] }, { "id": 3, "firstName": "Eve", "lastName": "Adams", "email": "eve@example.com", "username": "eve123", "createdAt": "2023-11-01T12:00:00.000Z", "phoneNumbers": ["234-567-8901"] }, { "id": 4, "firstName": "Alice", "lastName": "Johnson", "email": "alice@example.com", "username": "aliceUser", "createdAt": "2023-11-02T14:00:00.000Z", "phoneNumbers": ["123-456-7890"] } ] }
编写的内联模板如下:
{ "userList": [ {{#if (queryParamRaw 'filterBy')}} {{#each (filter (dataRaw 'userData' 'users') (object (queryParamRaw 'filterBy')=(queryParamRaw 'value')))}} {{#unless @first}},{{/unless}} {{{stringify this}}} {{/each}} {{else}} {{#each (dataRaw 'userData' 'users')}} {{#unless @first}},{{/unless}} {{stringify this}} {{/each}} {{/if}} ] }
运行时抛出错误:
Error while serving the content: Parse error on line 4: ...ParamRaw 'filterBy')=(queryParamRaw 'val -----------------------^ Expecting 'CLOSE_RAW_BLOCK', 'CLOSE', 'CLOSE_UNESCAPED', 'OPEN_SEXPR', 'CLOSE_SEXPR', 'ID', 'OPEN_BLOCK_PARAMS', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', got 'EQUALS'
错误原因
模板的核心问题在于**object helper的参数写法不符合Handlebars语法规范**:
- Mockoon内置的
objecthelper要求键和值作为独立的参数传递,不能使用key=value这种赋值语法(这不是Handlebars支持的参数传递方式)。 - 报错信息里的
got 'EQUALS'也明确指出,解析器遇到了不被允许的等号符号。
修正后的模板
方法1:正确使用object helper
将object的键值对拆分为两个独立参数,用空格分隔(Handlebars中helper参数用空格区分):
{ "userList": [ {{#if (queryParamRaw 'filterBy')}} {{#each (filter (dataRaw 'userData' 'users') (object (queryParamRaw 'filterBy') (queryParamRaw 'value')))}} {{#unless @first}},{{/unless}} {{{stringify this}}} {{/each}} {{else}} {{#each (dataRaw 'userData' 'users')}} {{#unless @first}},{{/unless}} {{stringify this}} {{/each}} {{/if}} ] }
方法2:改用where helper(更简洁)
如果Mockoon版本支持where helper,可以直接用它实现属性匹配过滤:
{ "userList": [ {{#if (queryParamRaw 'filterBy')}} {{#each (where (dataRaw 'userData' 'users') (queryParamRaw 'filterBy') (queryParamRaw 'value'))}} {{#unless @first}},{{/unless}} {{{stringify this}}} {{/each}} {{else}} {{#each (dataRaw 'userData' 'users')}} {{#unless @first}},{{/unless}} {{stringify this}} {{/each}} {{/if}} ] }
两种方法都能正确解析查询参数,返回符合filterBy和value条件的用户列表。
内容的提问来源于stack exchange,提问作者Kartik Singla
相关产品推荐
相关产品推荐

