Interagir com dados da tabela em uma instância ServiceNow
O Mobile SDK permite que você interaja com dados em tabelas que residem em sua instância ServiceNow. Você pode interagir com esses dados por meio da ServiceNow REST Table API usando a NowTableService() API que chama diretamente a interface REST ou por meio da NowGraphQLService() API que executa uma consulta GraphQL especificada em relação à REST GraphQL API.
Se você quiser retornar dados de várias tabelas em uma única chamada, precisará usar a API NowGraphQLService(). Se você precisar interagir com ServiceNow REST APIs diferentes da API de tabela, consulte Interagir com a REST API pública em uma instância ServiceNow.
Usando NowGraphQLService para interagir com ServiceNow tabelas
A classe NowGraphQLService fornece métodos que permitem construir e executar consultas GraphQL em uma tabela especificada dentro de sua instância ServiceNow se o usuário conectado tiver a autorização apropriada. Você pode definir todas as operações CRUD em sua consulta GraphQL.
/**
* Helper class used to handle different Now service instances.
*/
@Singleton
class SdkManager @Inject constructor() {
private var nowGraphQLService: NowGraphQLService? = null
/**
* Create the NowGraphQLService once in the lifetime of the application inside the Application class or another manager class
* that will be injected into other classes via dagger/hilt.
* NowGraphQLService should be created after initializing the NowSDK
*/
suspend fun getNowGraphQLService(): NowGraphQLService? {
if (nowGraphQLService != null) return nowGraphQLService
return NowDataSDK.makeGraphQLService(URL("https://instance-name.service-now.com")).getOrThrow()
.also { this.nowGraphQLService = it }
}
}suspend fun loadList() = withContext(Dispatchers.IO) {
val kbArticlesQuery = """
{
GlideRecord_Query {
kb_knowledge(queryConditions: "active=true^ORDERBYpublishedDESC"
pagination:{ limit: 10, offset: 0 }) {
_results {
sys_id { value },
number { displayValue },
short_description { displayValue },
author { displayValue }
published { displayValue }
}
}
}
}
"""
val graphQLService = sdkManager.getNowGraphQLService()
//graphQLService?.graphQLRequest(kbArticlesQuery)?.execute() can also be used
graphQLService?.graphQLRequest(kbArticlesQuery)?.enqueue(
{ response ->
response.body?.let {
val resultString = String(it)
}
}, { nowDataError ->
//handle error
})
}Usando NowTableService para interagir com ServiceNow tabelas
A classe NowTableService fornece métodos para executar operações CRUD nos registros em tabelas que residem em sua instância ServiceNow. Por meio dessa interface, é possível acessar diretamente qualquer um dos registros em qualquer tabela ServiceNow para a qual o usuário conectado esteja autorizado. O NowTableService oferece suporte à referência com pontos para campos de referência. Por exemplo, se uma tabela contiver uma referência à tabela Usuário, o valor de referência com pontos user.name retornará o nome do usuário.
Ao retornar os dados solicitados, todas as ACLs (Access Control Lists, listas de controle de acesso) aplicáveis são aplicadas aos dados, o que pode resultar em menos resultados do que o esperado ou em erros de autorização se o usuário autenticado não tiver direitos de acesso à tabela especificada.
/**
* Helper class used to handle different Now service instances. It has an application scope or is Singleton
*/
@Singleton
class SdkManager @Inject constructor() {
private var nowTableService: NowTableService? = null
/**
* Create the NowTableService once in the lifetime of the application inside the Application class or another manager class
* that will be injected into other classes via dagger/hilt.
* NowTableService should be created after initializing the NowSDK
*/
suspend fun getNowTableService(): NowTableService? {
if (nowTableService != null) return nowTableService
return NowDataSDK.makeTableService(URL("https://instance-name.service-now.com")).getOrThrow()
.also { this.nowTableService = it }
}
}
suspend fun loadCases() = withContext(Dispatchers.IO) {
val tableService = sdkManager.getNowTableService()
//configure what data to pass back
val fetchConfiguration = FetchConfiguration(Filter("active=true"), 10)
val response = runCatching {
tableService?.records(
"sn_customerservice_case",
fetchConfiguration
)?.execute()
}
if (response.isSuccess) {
val resultString = response.getOrNull()?.body?.let { String(it) }
} else {
//handle unsuccessful result
}
}Para obter exemplos de código adicionais usando os métodos NowTableService disponíveis, consulte a documentação da API NowTableService.