Exemplo 1: Recuperando todos os registros de incidentes de uma fonte externa

  • Versão de lançamento: Xanadu
  • Atualizado 1 de ago. de 2024
  • 4 min. de leitura
  • Estes são exemplos de definições de script que você pode criar para recuperação e armazenamento em cache de fontes externas à sua instância atual. Neste primeiro exemplo, criamos um script para carregar todos os registros de incidentes de uma fonte externa.

    Para obter informações sobre a API da tabela remota, consulte:
    /**
     * Using `v_query`, add the rows to `v_table`
     */
    (function executeQuery(v_table, v_query) {
    ​
    	fetchAllIncidents(v_table, v_query);
    ​
    	/**
    	 * fetch all incidents records from the remote instance
    	 */
    	function fetchAllIncidents(v_table, v_query) {
    		// Uses RestMessage with name 'Remote Instance Incidents' and function 'All Incidents'
    		// Create a RestMessage first which calls an external REST service
    		try {
    			var restMessage = new sn_ws.RESTMessageV2('Remote Instance Incidents', 'All Incidents');
    			var response = restMessage.execute();
    			var responseBody = response.getBody();
    			
    			// if REST call ends up in an error, set the last error message which shows up
    			// at the bottom of the list view
    			if (response.haveError()) {
    				v_query.setLastErrorMessage(response.getErrorMessage());
    				// can use gs.error() or gs.addErrorMessage() while debugging
    				// gs.debug() messages visible in session debugger
    				// gs.debug(response.getErrorMessage());
    				return;
    			}
    		} catch (ex) {
    			v_query.setLastErrorMessage(ex.message);
    			// gs.debug(ex.message);
    			return;
    		}
    ​
    		var transformerDefinition = getTransformerDefinition();
    		var transformer = new sn_tfrm.Transformer(transformerDefinition, responseBody);
    		// transformer parses the responseBody and extracts rows
    		while (transformer.transform()) {
    			// row is field-value map e.g. { active:"true", number: "INC0000001"}
    			var row = transformer.getRow();
    			// you may do any additional transformations to the row like GlideDuration, GlideDataTime etc. For example,
    			// row.duration = new GlideDuration(row.duration);
    ​
    			// finally add the row to the remote table
    			v_table.addRow(row);
    		}
    	}
    ​
    	/**
    	 * returns a sn_tfrm.TransformerDefinition, which defines the mapping of the table fields and elements in the response body
    	 */
    	function getTransformerDefinition() {
    		// create a rule list to map a field to its element path
    		var ruleList = new sn_tfrm.TransformerRuleList()
    			.fromJSON() // the response body is a JSON
    			// 'active' field maps to path '$.active'
    			.addRule("active", "$.active")
    			.addRule("caller_id", "$.caller_id.value")
    			.addRule("number", "$.number")
    			.addRule("short_description", "$.short_description")
    			.addRule("sys_id", "$.sys_id")
    			.addRule("updates", "$.sys_mod_count");
    ​
    		var recordPath = "$.result";
    		return new sn_tfrm.TransformerDefinition(ruleList, recordPath);
    	}
    	
    })(v_table, v_query);

    Estes snippets de código são importantes neste script:

    function fetchAllIncidents(v_table, v_query) {
    		// Uses RestMessage with name 'Remote Instance Incidents' and function 'All Incidents'
    		// Create a RestMessage first which calls an external REST service
    		try {
    			var restMessage = new sn_ws.RESTMessageV2('Remote Instance Incidents', 'All Incidents');
    			var response = restMessage.execute();
    			var responseBody = response.getBody();
    			
    			// if REST call ends up in an error, set the last error message which shows up
    			// at the bottom of the list view
    			if (response.haveError()) {
    				v_query.setLastErrorMessage(response.getErrorMessage());
    				// can use gs.error() or gs.addErrorMessage() while debugging
    				// gs.debug() messages visible in session debugger
    				// gs.debug(response.getErrorMessage());
    				return;
    			}
    		} catch (ex) {
    			v_query.setLastErrorMessage(ex.message);
    			// gs.debug(ex.message);
    			return;
    		}

    Você pode criar uma RestMessage e usá-la diretamente no script. Neste exemplo, ele usa uma API RESTMessageV2 com o nome de Incidentes de instância remotae a função Todos os incidentes, que obtém todos os dados do incidente. Depois que uma resposta é retornada do servidor, uma mensagem de erro é exibida se forem encontrados problemas na recuperação de dados.

    Nota:
    Para saber mais sobre o uso de RESTMessageV2 e como definir uma mensagem direta, consulte RESTMessageV2 - Com escopo, Global e Exemplo de RESTMessageV2 direta.

    Se nenhum problema for encontrado na recuperação de dados, ele obterá o corpo dos dados para os registros.

    		var transformerDefinition = getTransformerDefinition();
    		var transformer = new sn_tfrm.Transformer(transformerDefinition, responseBody);
    		// transformer parses the responseBody and extracts rows
    		while (transformer.transform()) {
    			// row is field-value map e.g. { active:"true", number: "INC0000001"}
    			var row = transformer.getRow();
    			// you may do any additional transformations to the row like GlideDuration, GlideDataTime etc. For example,
    			// row.duration = new GlideDuration(row.duration);
    ​
    			// finally add the row to the remote table
    			v_table.addRow(row);
    

    Em seguida, ele usa a API do Transformador para executar as transformações de dados necessárias, extrai linhas e adiciona uma linha para cada registro à tabela remota.

    /**
    	 * returns a sn_tfrm.TransformerDefinition, which defines the mapping of the table fields and elements in the response body
    	 */
    	function getTransformerDefinition() {
    		// create a rule list to map a field to its element path
    		var ruleList = new sn_tfrm.TransformerRuleList()
    			.fromJSON() // the response body is a JSON
    			// 'active' field maps to path '$.active'
    			.addRule("active", "$.active")
    			.addRule("caller_id", "$.caller_id.value")
    			.addRule("number", "$.number")
    			.addRule("short_description", "$.short_description")
    			.addRule("sys_id", "$.sys_id")
    			.addRule("updates", "$.sys_mod_count");
    ​
    		var recordPath = "$.result";
    		return new sn_tfrm.TransformerDefinition(ruleList, recordPath);
    	}
    	
    })(v_table, v_query);
    
    getTransformerDefinition define o esquema do registro no corpo da resposta da API externa. Ele mapeia cada um dos campos no script da tabela para um elemento no registro externo. Quaisquer elementos de dados externos fora deste mapeamento não são compatíveis ou recuperados.
    Nota:
    Você deve mapear um sys_id na definição do transformador para um elemento nos dados externos. Nesse caso, o sys_id é mapeado para o sys_id do incidente externo. O tamanho máximo do sys_id é de 32 caracteres. Você faz este mapeamento de sys_id para que os formulários que usam os dados externos possam operar corretamente.