Proveedores de datos personalizados
Creación de un Script para el proveedor de datos Enterprise que importa datos JSON
---------------------------------------------------------------------------------------------------------
-- JSON 2024 Proveedor de datos personalizado.
--
-- Sólo complatible con la versión 2024 de EasyCatalog
--
-- Las funciones clave se ejecutan durante la recuperación y actualización de los datos. El script se inicializa y se ejecuta bajo demanda,
-- como tal no mantiene el estado y se basa en los ajustes de 'configuración' proporcionados de llamada en llamada para representar
-- la configuración actualizada del origen de datos.
--
-- Creacion del origen de datos
-- La secuencia de llamadas durante la creación de un nuevo origen de datos es la siguiente:
-- 1. Initialize() - devuelve una tabla de ajustes por defecto, que se almacena en el archivo datasource.xml del origen de datos.
-- 2. ConfigureUI(config) Presenta al usuario los ajustes de configuración para permitir su modificación.
-- 3. Synchronize(datasource, config) - se ejecuta después de la configuración para recuperar un RECORDSET completo.
--
-- Actualización del Origen de Datos
-- SaveRecords(config, datasource, records) - Se ejecuta cuando el usuario selecciona "Actualizar Origen de Datos".
-- es la responsable de importar los cambios al origen de datos y eliminar la etiqueta de actualización.
--
---------------------------------------------------------------------------------------------------------
--
-- Oct 2023 Creado v1.0.0
--
---------------------------------------------------------------------------------------------------------
--[[
Estructura del archivo JSON de ejemplo:
{
"products": [
{
"id": "12345",
"name": "Product A",
"description": "This is Product A, a high-quality product.",
"price": 19.99,
"category": "Electronics",
"stock": 50
},
{
"id": "67890",
"name": "Product B",
"description": "Product B is a versatile and popular item.",
"price": 29.99,
"category": "Clothing",
"stock": 100
},
{
"id": "54321",
"name": "Product C",
"description": "Product C is a premium accessory.",
"price": 39.99,
"category": "Accessories",
"stock": 25
}
]
}
]];
-- Especifica el JSONPath de cada 'registro' en los datos
local record_JSONPath = "$.products[*]"
-- Especifica los campos que se van a extraer en cada registro
local fields_with_options = {
{ name = "id", jsonpath = "$.id", key = "true"},
{ name = "name", jsonpath = "$.name"},
{ name = "description", jsonpath = "$.description"},
{ name = "price", jsonpath = "$.price"},
{ name = "stock", jsonpath = "$.stock"}
};
------------------------------------------------------------------------------------------------------------------------
-- load_file
------------------------------------------------------------------------------------------------------------------------
function load_file(path)
local file = io.open(path, "r");
if not file then return nil end
local content = file:read "*a" -- *a o *all lee todo el archivo
file:close();
return content
end
------------------------------------------------------------------------------------------------------------------------
-- getActualScriptVersion
------------------------------------------------------------------------------------------------------------------------
function getActualScriptVersion()
local info = GetInfo();
return 'v' .. info.version;
end
---------------------------------------------------------------------------------------------------------
-- Initialize - Define los ajustes por defecto del Origen de Datos.
-- Devuelve una tabla de ajustes.
---------------------------------------------------------------------------------------------------------
function Initialize()
config = {}
config.name = "JSON 2024";
config.initialized = false;
config.JSONfile = '';
config.version = getActualScriptVersion();
return config;
end
---------------------------------------------------------------------------------------------------------
-- validatemethod
---------------------------------------------------------------------------------------------------------
function validatemethod(dialog)
local name = dialog:getwidget("Name").value;
if name == "" then
DIALOG.alert("please enter a valid name.");
return "Name";
end
local file = dialog:getwidget("edit_file").value;
if file == "" then
DIALOG.alert("please select a JSON file to process.");
return "edit_file";
end
return "";
end
---------------------------------------------------------------------------------------------------------
-- setDialogWidget
---------------------------------------------------------------------------------------------------------
function setDialogWidget(pConfigdialog, pName, pValue)
local widget = pConfigdialog:getwidget(pName);
widget.content = pValue;
pConfigdialog:setwidget(widget);
end
---------------------------------------------------------------------------------------------------------
-- get_JSON_file_location
---------------------------------------------------------------------------------------------------------
function get_JSON_file_location()
-- ask user for JSON file location
local done, path = DIALOG.choosefile("Choose JSON file");
return done, path;
end
---------------------------------------------------------------------------------------------------------
-- chooseButtonAction
---------------------------------------------------------------------------------------------------------
chooseButtonAction = function(configdialog)
local done, path = get_JSON_file_location(); -- JSON file location
if (done) then
actionConfig.JSONfile = path;
setDialogWidget(configdialog, "edit_file", actionConfig.JSONfile);
end
end
---------------------------------------------------------------------------------------------------------
-- ConfigureUI
---------------------------------------------------------------------------------------------------------
function ConfigureUI(config)
local enable_name = false;
actionConfig = config;
if config.initialized == false then
enable_name = true;
end
local title_new = "New JSON 2024 Data Source";
local title_edit = "JSON 2024 Data Source";
local the_title = title_new;
if enable_name == false then
the_title = title_edit;
end
configdialog = DIALOG.new( { title = the_title, validate = validatemethod } );
local name_top = 20;
local file_top = 20+(25*1);
local choose_button_top = 20+(25*2);
local button_top = 20+(25*3)+10;
local widget_left = 90;
local static_right = widget_left;
local widget_right = 500;
local choose_button_width = 100;
local choose_button_left = widget_right - choose_button_width;
configdialog:addwidget(
{
{ type = "statictext", title = "Name:", align = "left", left = 20, top = name_top, right = static_right, height = 20 },
{ type = "editbox", id = "Name", left = widget_left, top = name_top, right = widget_right, height = 20, content = config.name, enable = enable_name },
{ type = "statictext", title = "File:", align = "left", left = 20, top = file_top, right = static_right, height = 20 },
{ type = "editbox", id = "edit_file", left = widget_left, top = file_top, right = widget_right, height = 20, content = config.JSONfile, enable = true },
{ type = "button", id = "edit_file_choose", title = "Choose", left = choose_button_left, top = choose_button_top, width = choose_button_width, heigth = 20, onchange = chooseButtonAction},
{ type = "cancelbutton", title = "Cancel", id = "cancel", left = 270, top = button_top, width = 80, heigth = 20, },
{ type = "okbutton", title = "Ok", id = "ok", left = 270+80+20, top = button_top, width = 80, heigth = 20 },
}
);
if configdialog:open() then
config.name = configdialog:getwidget("Name").content;
config.JSONfile = configdialog:getwidget("edit_file").content;
return config;
end
end
---------------------------------------------------------------------------------------------------------
-- Synchronize
-- config : Parámetros de configuración (in/out). Si se modifica, actualizará el archivo datasource.xml
-- datasource : Objeto del tipo Origen de Datos
-- Returns : nuevo RECORDSET o nil si se cancela
---------------------------------------------------------------------------------------------------------
function Synchronize(config, datasource)
config.initialized = true;
return RECORDSET.new(fields_with_options, create_records_from_json(config));
end
---------------------------------------------------------------------------------------------------------
-- SaveRecords
-- Actualiza los datos en el Origen de Datos
-- config : Parámetros de configuración (in/out)
---------------------------------------------------------------------------------------------------------
function SaveRecords(config, datasource, records)
for i=1,records:size() do
record = records:getrecord(i);
for x=1, record:size() do
field = record:field(x);
if field:getupdatestate() & 2 == 2 then
field:setupdatestate(0);
end
end
end
end
---------------------------------------------------------------------------------------------------------
-- GetReleaseNotes
---------------------------------------------------------------------------------------------------------
function GetReleaseNotes()
local body = "";
body = body .. "<h1>JSON 2024 Release Notes</h1>";
body = body .. "<h3>v1.0.0</h3>";
body = body .. "<ul>";
body = body .. "<li>A sample script using JSONPath to parse JSON data</li>";
body = body .. "</ul>";
c = {
title = "JSON 2024 Release Notes",
body = body,
};
return c;
end
---------------------------------------------------------------------------------------------------------
-- GetInfo
---------------------------------------------------------------------------------------------------------
function GetInfo()
c = {
url = "https://www.65bit.com/docs/creating-custom-json-data-providers/",
name = "JSON 2024 File Sample",
version = "1.0.0",
};
return c;
end
---------------------------------------------------------------------------------------------------------
-- Dada una URI, devuelve true si la descarga se puede gestionar desde este script
---------------------------------------------------------------------------------------------------------
function CanResolveAssetURI(field, uri)
return false;
end
---------------------------------------------------------------------------------------------------------
-- Convierte una URI en una ubicación cualificada, desde la cual se determina la ubicación de almacenamiento
---------------------------------------------------------------------------------------------------------
function ResolveAssetURI(config, uri)
return uri;
end
---------------------------------------------------------------------------------------------------------
-- location : resultado de 'ResolveAssetURI'
-- filepath : ruta completa a la caché local
---------------------------------------------------------------------------------------------------------
function GetAsset(config, location, filepath)
return false;
end
---------------------------------------------------------------------------------------------------------
-- Devuelve una tabla de registros con los campos especificados en 'fields_with_options'
-- config : Tabla de configuración
---------------------------------------------------------------------------------------------------------
function create_records_from_json(config)
json = load_file(config.JSONfile);
if json == nil or json == "" then
error("JSON empty or cannot be loaded");
end
records = {}
table_of_records, err = jsonarraytotable(json, record_JSONPath);
if table_of_records == nil then
error(err);
end
for r = 1, #table_of_records do
record_json = table_of_records[r];
if record_json ~= "" and record_json ~= nil then
r = {}
for i = 1, #fields_with_options do
r[fields_with_options[i].name] = processjson('jsonpath', record_json, fields_with_options[i].jsonpath);
end
table.insert(records, r);
end
end
return records;
endÚltima actualización
¿Te fue útil?