feat: improved input format

This commit is contained in:
Morten Olsen
2025-05-18 20:26:15 +02:00
parent bc92c91ff8
commit 1cb885bb32
2 changed files with 39 additions and 4 deletions

View File

@@ -338,6 +338,17 @@ The `::md` directive embeds another markdown document.
- `hidden`: If present, the actual content (markdown) of the embedded document will not be rendered in the output. However, any `http` requests within the embedded document _are still processed_, and their `request` and `response` data become available in the parent document's templating context (via `requests.id` and `responses.id`). This is useful if you only want to execute the requests from an included file (e.g., a common setup sequence) and use their results, without displaying the embedded file's content.
- Example: `::md[./setup_requests.md]{hidden}`
#### `::input[{name}]` Directive Options
The `::input` directive is used to declare expected input variables
- **Variable Name:** The first argument (required) is the name of the variable
- Example: `::input[myVariable]` will define `input.myVariable`
- `required`: If present it will require that the variable is provided
- `default={value}`: Defines the default value if no value has been provided
- `format=string|number|bool|json|date`: If provided the value will be parsed using the specified format
- ``
## Command-Line Interface (CLI)
The `httpmd` tool provides the following commands:

View File

@@ -22,12 +22,36 @@ const inputHandler: ExecutionHandler = ({
context.input[name] = node.attributes.default;
}
if (node.attributes?.format === 'number' && context.input[name] !== undefined) {
if (node.attributes?.format && context.input[name] !== undefined) {
const format = node.attributes.format;
if (format === 'number') {
context.input[name] = Number(context.input[name]);
if (context.input[name] !== undefined && isNaN(Number(context.input[name]))) {
throw new Error(`Input "${name}" must be a number, but got "${context.input[name]}"`);
}
}
if (format === 'boolean') {
context.input[name] = context.input[name] === 'true';
}
if (format === 'string') {
context.input[name] = String(context.input[name]);
}
if (format === 'json') {
try {
context.input[name] = JSON.parse(String(context.input[name]));
} catch (error) {
throw new Error(`Input "${name}" must be a valid JSON, but got "${context.input[name]}"`);
}
}
if (format === 'date') {
const date = new Date(context.input[name] as string);
if (isNaN(date.getTime())) {
throw new Error(`Input "${name}" must be a valid date, but got "${context.input[name]}"`);
}
context.input[name] = date;
}
}
if (!parent || !('children' in parent) || index === undefined) {
throw new Error('Parent node is required');