Conditional Logic
Make your API dynamic by showing, hiding, or changing data based on the incoming request.
The Context Object
When a request hits your endpoint, Mock66 captures the details and exposes them to your schema via a global object called req.
| Property | Description | Example Usage |
|---|---|---|
| req.query | URL Query Parameters (after the ?) | req.query.role == 'admin' |
| req.body | JSON Body payload (for POST/PUT requests) | req.body.type == 'pro' |
| req.params | Dynamic Route Parameters (e.g., /users/:id) | req.params.id == '123' |
Writing Conditions
A condition is simply a JavaScript Expression that returns true or false.
- If the result is
true, the field is included in the response. - If the result is
false(or throws an error), the field is completely removed from the JSON output. - Use
==for loose equality to handle string/number mismatches in query params. - See complex examples in the JEXL documentation.
Valid Expressions:
Using the Editor
You don't need to write code files. You can attach conditions directly to any field in the Visual Builder.
1. Open Field Settings
Hover over any field row in the builder. Click the icon on the right side.
2. Enter the Expression
Find the input labeled "Conditional Logic". Paste your JavaScript expression there.
Visual Designer
Common Recipes
Role-Based Visibility
Hide sensitive fields like `revenue` unless the user is an admin.
Simulating Errors
Add an `error` object, but only show it if specifically requested.
Simulating Pagination
You can mimic pagination logic using standard conditionals on items inside an array.
Create multiple items in an array, but set conditions so they only appear for specific page numbers.
- Create a root array with 4 items.
- Items 1 & 2: Set condition to:
!req.query.page || req.query.page == '1' - Items 3 & 4: Set condition to:
req.query.page == '2'
/api/users?page=2 will hide the first two items and only return the last two.