> For the complete documentation index, see [llms.txt](https://docs.kiloiot.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.kiloiot.io/kilo-docs-pt/kilo-center/kilo-mioty-service-center/integrations/api-reference/javascript-examples.md).

# Exemplos em JavaScript

Exemplos executáveis em Node.js para a API gRPC do KiloCenter — instale @grpc/grpc-js com carregamento dinâmico de proto e chame métodos.

Esta página fornece exemplos executáveis em Node.js para a API gRPC do KiloCenter usando carregamento dinâmico de proto. Para a referência completa da API, consulte a Referência da API.

Para documentação geral do gRPC em Node.js, consulte [grpc.io/docs/languages/node](https://grpc.io/docs/languages/node/).

### Pré-requisitos

> Todos os comandos deste guia assumem que o seu diretório de trabalho é `kilocenter-modules/`.

Instale os pacotes gRPC e proto-loader:

```bash
npm install @grpc/grpc-js @grpc/proto-loader
```

Não é necessária a geração de stubs — `@grpc/proto-loader` carrega `.proto` ficheiros em tempo de execução. Certifique-se de que os ficheiros proto estão acessíveis nos caminhos referenciados abaixo (relativos à raiz do repositório KiloCenter):

* `KC-Core/api/proto/kilocenter.proto`
* `KC-Core/api/proto/core.proto`
* `KC-Core/api/proto/identity.proto`

### Obter estado do sistema

Obtém o estado atual do sistema, incluindo versão, tempo de atividade e estado dos serviços.

```javascript
const grpc = require("@grpc/grpc-js");
const protoLoader = require("@grpc/proto-loader");

// Endpoint gRPC do KiloCenter KC-Gateway
const server = "localhost:9090";

const packageDef = protoLoader.loadSync("KC-Core/api/proto/kilocenter.proto", {
  keepCase: false,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
  includeDirs: ["KC-Core/api/proto"],
});

const proto = grpc.loadPackageDefinition(packageDef);
const client = new proto.kilocenter.api.v1.KiloCenterService(
  server,
  grpc.credentials.createInsecure()
);

client.GetSystemStatus({}, (err, resp) => {
  if (err) {
    console.error("Falha em GetSystemStatus:", err.message);
    process.exit(1);
  }

  console.log("Versão:            ", resp.version);
  console.log("Estado:             ", resp.status);
  console.log("Tempo de atividade: ", resp.uptime);
  console.log("Endpoints ativos:   ", resp.activeEndpoints);
  console.log("Estações base ativas:", resp.activeBasestations);
  console.log("Mensagens processadas: ", resp.messagesProcessed);

  for (const svc of resp.services) {
    console.log(`  Serviço: ${svc.name}  healthy=${svc.healthy}  latência=${svc.latencyMs}ms`);
  }
});
```

### Listar endpoints

Lista os endpoints registados com suporte para paginação. Perfil de alto volume: tamanho de página predefinido 100, máximo 1000.

```javascript
const grpc = require("@grpc/grpc-js");
const protoLoader = require("@grpc/proto-loader");

const server = "localhost:9090";

const packageDef = protoLoader.loadSync("KC-Core/api/proto/kilocenter.proto", {
  keepCase: false,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
  includeDirs: ["KC-Core/api/proto"],
});

const proto = grpc.loadPackageDefinition(packageDef);
const client = new proto.kilocenter.api.v1.KiloCenterService(
  server,
  grpc.credentials.createInsecure()
);

function listEndpoints(pageToken = "") {
  client.ListEndPoints({ pageSize: 100, pageToken }, (err, resp) => {
    if (err) {
      console.error("Falha em ListEndPoints:", err.message);
      process.exit(1);
    }

    console.log("Total de endpoints:", resp.totalCount);

    for (const ep of resp.endpoints) {
      console.log(`  EUI: ${ep.epEui}  Nome: ${ep.name}  Estado: ${ep.status}  Classe: ${ep.epClass}`);
    }

    if (resp.nextPageToken) {
      listEndpoints(resp.nextPageToken);
    }
  });
}

listEndpoints();
```

### Autenticação

#### Edição Comunitária

A Edição Comunitária é executada em modo de inquilino único com autenticação e aplicação da organização desativadas (`auth.enabled: false`, `org_enforcement_enabled: false`). Os exemplos acima funcionam sem quaisquer cabeçalhos.

#### Enterprise: Principal do utilizador JWT

Requer três cabeçalhos: `authorization`, `x-organization-id`, e `x-user-id`. A `x-user-id` o valor deve corresponder ao utilizador autenticado no JWT. Em falta `x-user-id` retorna `ErrTokenUserIDHeaderRequired`; uma incompatibilidade retorna `ErrTokenIdentityMismatch`.

```javascript
const token = "your-jwt-token";
const orgId = "your-organization-uuid";
const userId = "your-user-uuid";

const metadata = new grpc.Metadata();
metadata.set("authorization", "Bearer " + token);
metadata.set("x-organization-id", orgId);
metadata.set("x-user-id", userId);

client.ListEndPoints({ pageSize: 100 }, metadata, (err, resp) => {
  if (err) {
    console.error("Falha em ListEndPoints:", err.message);
    return;
  }
  console.log("Total de endpoints:", resp.totalCount);
});
```

#### Enterprise: Chave API da conta de serviço

Requer dois cabeçalhos: `authorization` e `x-organization-id`. Não **não** envie `x-user-id` — incluí-lo retorna `ErrTokenIdentityMismatch` para evitar injeção de utilizador.

```javascript
const apiKey = "your-api-key";
const orgId = "your-organization-uuid";

const metadata = new grpc.Metadata();
metadata.set("authorization", "Bearer " + apiKey);
metadata.set("x-organization-id", orgId);

client.ListEndPoints({ pageSize: 100 }, metadata, (err, resp) => {
  if (err) {
    console.error("Falha em ListEndPoints:", err.message);
    return;
  }
  console.log("Total de endpoints:", resp.totalCount);
});
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.kiloiot.io/kilo-docs-pt/kilo-center/kilo-mioty-service-center/integrations/api-reference/javascript-examples.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
