> 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-de/kilo-center/kilo-mioty-service-center/integrations/api-reference/javascript-examples.md).

# JavaScript-Beispiele

Ausführbare Node.js-Beispiele für die KiloCenter-gRPC-API — installieren Sie @grpc/grpc-js mit dynamischem Proto-Loading und rufen Sie Methoden auf.

Diese Seite bietet ausführbare Node.js-Beispiele für die KiloCenter gRPC API unter Verwendung von dynamischem Proto-Laden. Die vollständige API-Referenz finden Sie unter API Reference.

Für allgemeine Node.js-gRPC-Dokumentation siehe [grpc.io/docs/languages/node](https://grpc.io/docs/languages/node/).

### Voraussetzungen

> Alle Befehle in diesem Leitfaden setzen voraus, dass Ihr Arbeitsverzeichnis `kilocenter-modules/`.

Installieren Sie die gRPC- und proto-loader-Pakete:

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

Es ist keine Stub-Generierung erforderlich — `@grpc/proto-loader` lädt `.proto` Dateien zur Laufzeit. Stellen Sie sicher, dass die Proto-Dateien unter den unten referenzierten Pfaden zugänglich sind (relativ zum Stammverzeichnis des KiloCenter-Repositorys):

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

### Systemstatus abrufen

Ruft den aktuellen Systemstatus ab, einschließlich Version, Laufzeit und Dienstzustand.

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

// KiloCenter KC-Gateway gRPC-Endpunkt
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("GetSystemStatus failed:", err.message);
    process.exit(1);
  }

  console.log("Version:            ", resp.version);
  console.log("Status:             ", resp.status);
  console.log("Uptime:             ", resp.uptime);
  console.log("Active Endpoints:   ", resp.activeEndpoints);
  console.log("Active Base Stations:", resp.activeBasestations);
  console.log("Messages Processed: ", resp.messagesProcessed);

  for (const svc of resp.services) {
    console.log(`  Service: ${svc.name}  healthy=${svc.healthy}  latency=${svc.latencyMs}ms`);
  }
});
```

### Endpunkte auflisten

Listet registrierte Endpunkte mit Paginierungsunterstützung auf. Hochvolumenprofil: Standardseitengröße 100, Maximum 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("ListEndPoints failed:", err.message);
      process.exit(1);
    }

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

    for (const ep of resp.endpoints) {
      console.log(`  EUI: ${ep.epEui}  Name: ${ep.name}  Status: ${ep.status}  Class: ${ep.epClass}`);
    }

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

listEndpoints();
```

### Authentifizierung

#### Community Edition

Die Community Edition läuft im Single-Tenant-Modus, wobei die Authentifizierung und die Erzwingung von Organisationen deaktiviert sind (`auth.enabled: false`, `org_enforcement_enabled: false`). Die obigen Beispiele funktionieren ohne Header.

#### Enterprise: JWT-Benutzerprinzipal

Erfordert drei Header: `authorization`, `x-organization-id`, und `x-user-id`. Der `x-user-id` Der Wert muss mit dem im JWT authentifizierten Benutzer übereinstimmen. Fehlt `x-user-id` gibt `ErrTokenUserIDHeaderRequired`; bei einer Abweichung wird `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("ListEndPoints failed:", err.message);
    return;
  }
  console.log("Total endpoints:", resp.totalCount);
});
```

#### Enterprise: Service-Account-API-Schlüssel

Erfordert zwei Header: `authorization` und `x-organization-id`. Tun **nicht** senden `x-user-id` — das Einfügen davon gibt `ErrTokenIdentityMismatch` um Benutzerinjektion zu verhindern.

```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("ListEndPoints failed:", err.message);
    return;
  }
  console.log("Total 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-de/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.
