feat: implement post-response script handling and update environment variables

This commit is contained in:
Udhay-Adithya
2025-05-02 01:26:52 +05:30
parent 0645ab1a33
commit c2c67a7fca
3 changed files with 163 additions and 4 deletions

View File

@@ -6,6 +6,7 @@ import 'dart:developer';
import 'package:apidash/consts.dart';
import 'package:apidash/models/request_model.dart';
import 'package:apidash_core/models/http_request_model.dart';
import 'package:apidash_core/models/http_response_model.dart';
import 'package:flutter/services.dart';
import 'package:flutter_js/flutter_js.dart';
@@ -133,7 +134,6 @@ Future<
})(); // Immediately invoke the function
""";
// TODO: Do something better to avoid null check here.
HttpRequestModel resultingRequest = httpRequest!;
Map<String, dynamic> resultingEnvironment = Map.from(activeEnvironment);
@@ -177,6 +177,101 @@ Future<
);
}
Future<
({
HttpResponseModel updatedResponse,
Map<String, dynamic> updatedEnvironment
})> executePostResponseScript({
required RequestModel currentRequestModel,
required Map<String, dynamic> activeEnvironment,
}) async {
if (currentRequestModel.postRequestScript.trim().isEmpty) {
// No script, return original data
// return (
// updatedRequest: currentRequestModel.httpRequestModel,
// updatedEnvironment: activeEnvironment
// );
}
final httpRequest = currentRequestModel.httpRequestModel;
final httpResponse = currentRequestModel.httpResponseModel;
final userScript = currentRequestModel.postRequestScript;
// Prepare Data
final requestJson = jsonEncode(httpRequest?.toJson());
final responseJson = jsonEncode(httpResponse?.toJson());
final environmentJson = jsonEncode(activeEnvironment);
// Inject data as JS variables
// Escape strings properly if embedding directly
final dataInjection = """
var injectedRequestJson = ${jsEscapeString(requestJson)};
var injectedEnvironmentJson = ${jsEscapeString(environmentJson)};
var injectedResponseJson = ${jsEscapeString(responseJson)};
""";
// Concatenate & Add Return
final fullScript = """
(function() {
// --- Data Injection (now constants within the IIFE scope) ---
$dataInjection
// --- Setup Script (will declare variables within the IIFE scope) ---
$setupScript
// --- User Script (will execute within the IIFE scope)---
$userScript
// --- Return Result (accesses variables from the IIFE scope) ---
return JSON.stringify({ response: response, environment: environment });
})(); // Immediately invoke the function
""";
// TODO: Do something better to avoid null check here.
// HttpRequestModel resultingRequest = httpRequest!;
HttpResponseModel resultingResponse = httpResponse!;
Map<String, dynamic> resultingEnvironment = Map.from(activeEnvironment);
try {
// Execute
final JsEvalResult result = jsRuntime.evaluate(fullScript);
// Process Results
if (result.isError) {
print("Post-Response script execution error: ${result.stringResult}");
// TODO: Handle error - maybe show in UI, keep original request/env
} else if (result.stringResult.isNotEmpty) {
final resultMap = jsonDecode(result.stringResult);
log(resultMap['response'].toString());
if (resultMap is Map<String, dynamic>) {
// Deserialize Request
if (resultMap.containsKey('response') && resultMap['response'] is Map) {
try {
resultingResponse = HttpResponseModel.fromJson(
Map<String, Object?>.from(resultMap['response']));
} catch (e) {
print("Error deserializing modified response from script: $e");
//TODO: Handle error - maybe keep original response?
}
}
// Get Environment Modifications
if (resultMap.containsKey('environment') &&
resultMap['environment'] is Map) {
resultingEnvironment =
Map<String, dynamic>.from(resultMap['environment']);
}
}
}
} catch (e) {
print("Dart-level error during post-response script execution: $e");
}
return (
updatedResponse: resultingResponse,
updatedEnvironment: resultingEnvironment
);
}
// Helper to properly escape strings for JS embedding
String jsEscapeString(String s) {
return jsonEncode(