From 7291dc9272acc6b42c3f2986c86d3b1c281912ab Mon Sep 17 00:00:00 2001 From: Oliver Date: Thu, 15 Jul 2021 23:58:09 +1000 Subject: [PATCH] Extract field information from the server --- lib/api_form.dart | 76 ++++++++++++++++++++++++++++++++++++++++ lib/inventree/model.dart | 3 +- 2 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 lib/api_form.dart diff --git a/lib/api_form.dart b/lib/api_form.dart new file mode 100644 index 00000000..21d037d1 --- /dev/null +++ b/lib/api_form.dart @@ -0,0 +1,76 @@ +import 'dart:convert'; + +import 'package:InvenTree/api.dart'; + +/* + * Extract field options from a returned OPTIONS request + */ +Map extractFields(dynamic options) { + + if (options == null) { + return {}; + } + + if (!options.containsKey("actions")) { + return {}; + } + + var actions = options["actions"]; + + return actions["POST"] ?? actions["PUT"] ?? actions["PATCH"] ?? {}; +} + +/* + * Launch an API-driven form, + * which uses the OPTIONS metadata (at the provided URL) + * to determine how the form elements should be rendered! + */ + +Future launchApiForm(String url, Map fields, {String method = "PATCH"}) async { + + dynamic options = await InvenTreeAPI().options(url); + + // null response from server + if (options == null) { + return false; + } + + var availableFields = extractFields(options); + + if (availableFields.isEmpty) { + print("Empty fields {} returned from ${url}"); + return false; + } + + // Iterate through the provided fields we wish to display + for (String fieldName in fields.keys) { + + // Check that the field is actually available at the API endpoint + if (!availableFields.containsKey(fieldName)) { + print("Field '${fieldName}' not available at '${url}'"); + continue; + } + + var remoteField = availableFields[fieldName] ?? {}; + var localField = fields[fieldName] ?? {}; + + // Override defined field parameters, if provided + for (String key in localField.keys) { + // Special consideration + if (key == "filters") { + + } else { + String? val = localField[key]; + + if (val != null) { + remoteField[key] = val; + } + } + } + + print("${fieldName} -> ${remoteField.toString()}"); + + } + + return true; +} \ No newline at end of file diff --git a/lib/inventree/model.dart b/lib/inventree/model.dart index 76d558b3..3cc6b916 100644 --- a/lib/inventree/model.dart +++ b/lib/inventree/model.dart @@ -126,8 +126,7 @@ class InvenTreeModel { } // Return the API detail endpoint for this Model object - String get url => "${URL}/${pk}/"; - + String get url => "${URL}/${pk}/".replaceAll("//", "/"); // Search this Model type in the database Future> search(BuildContext context, String searchTerm, {Map filters = const {}}) async {