npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

powerbi-client-js

v1.0.1

Published

A JavaScript/TypeScript client for Power BI REST API with support for DAX queries and table operations

Readme

powerbi-client-js

Cliente TypeScript/JavaScript para la API REST de Power BI. Proporciona métodos para ejecutar consultas DAX y operaciones sobre tablas, con manejo de token integrado.

Características

  • 🔐 Autenticación OAuth2 con Azure AD (Service Principal)
  • 📊 Consultas a tablas con TOPN y selección de columnas
  • 🔍 Ejecución de consultas DAX personalizadas
  • 📋 Obtención de esquema de tablas (getTableSchema)
  • 🛡️ Manejo de errores y mensajes según HTTP status
  • 🧩 Tipos TypeScript incluidos (dist/*.d.ts)

Instalación

npm install powerbi-client-js

O en un mono-repo local:

npm install ./powerbi-client-module

Inicio rápido

import { PowerBIClient } from 'powerbi-client-js';

const client = new PowerBIClient({
  tenantId: process.env.AZURE_TENANT_ID!,
  clientId: process.env.AZURE_CLIENT_ID!,
  clientSecret: process.env.AZURE_CLIENT_SECRET!,
  groupId: process.env.POWERBI_GROUP_ID!,
  datasetId: process.env.POWERBI_DATASET_ID!
});

// Consultar tabla
const table = await client.queryTable('Sales', 10, ['OrderId', 'Amount']);
if (table.success) {
  console.log(table.data);
}

// Ejecutar DAX
const dax = await client.executeDaxQuery("EVALUATE TOPN(5, 'Sales')");
console.log(dax.data);

Configuración

interface PowerBIConfig {
  tenantId: string;
  clientId: string;
  clientSecret: string;
  groupId: string;
  datasetId: string;
}

API

new PowerBIClient(config)

Inicializa el cliente con la configuración.

executeDaxQuery(query, options?) => Promise<QueryResult>

Ejecuta una consulta DAX.

queryTable(tableName, topN?, columns?, options?) => Promise<QueryResult>

Consulta una tabla con límite de filas y selección opcional de columnas.

queryTableById(tableName, idColumn, idValue, topN?, columns?, options?) => Promise<QueryResult>

Consulta una tabla aplicando un filtro simple por columna/valor.

queryTables(tables, options?) => Promise<QueryResult[]>

Ejecuta varias consultas de tablas en una sola llamada.

executeDaxQueries(queries, options?) => Promise<QueryResult[]>

Ejecuta múltiples consultas DAX.

getTableSchema(tableName) => Promise<QueryResult>

Obtiene el esquema de una tabla.

Formato de respuesta

Todas las operaciones retornan QueryResult:

interface QueryResult {
  success: boolean;
  data: Record<string, unknown>[];
  rowCount: number;
  query?: string;
  error?: string;
}

Ejemplo:

{
  "success": true,
  "data": [
    { "OrderId": 123, "Amount": 150.0 }
  ],
  "rowCount": 1,
  "query": "EVALUATE TOPN(1, 'Sales')"
}

Ejemplos de uso

Tabla básica

const res = await client.queryTable('Sales', 20, ['OrderId', 'CustomerName', 'Amount']);
if (res.success) {
  console.log(`Filas: ${res.rowCount}`, res.data);
}

DAX avanzada

const daxQuery = `
EVALUATE
TOPN(10,
  ADDCOLUMNS(
    SUMMARIZE(Sales, Products[ProductName]),
    "TotalRevenue", SUM(Sales[Amount])
  ),
  [TotalRevenue], DESC
)`;
const res = await client.executeDaxQuery(daxQuery);
console.log(res.data);

Varias tablas

const res = await client.queryTables([
  { name: 'Sales', topN: 50 },
  { name: 'Products', topN: 25 }
]);
console.log(res.map(r => r.rowCount));

Helper getRowBy

Ejemplo de helper para obtener una fila específica usando el cliente y un objeto where sencillo:

import { PowerBIClient } from 'powerbi-client-js';

const client = new PowerBIClient({
  tenantId: process.env.AZURE_TENANT_ID!,
  clientId: process.env.AZURE_CLIENT_ID!,
  clientSecret: process.env.AZURE_CLIENT_SECRET!,
  groupId: process.env.POWERBI_GROUP_ID!,
  datasetId: process.env.POWERBI_DATASET_ID!
});

function buildFilterExpr(tableName: string, where: Record<string, unknown>): string {
  const parts: string[] = [];
  for (const [col, val] of Object.entries(where)) {
    const colRef = `'${tableName}'[${col}]`;
    if (typeof val === 'string') {
      parts.push(`${colRef} = "${val.replace(/"/g, '\\"')}"`);
    } else if (typeof val === 'number') {
      parts.push(`${colRef} = ${val}`);
    } else if (typeof val === 'boolean') {
      parts.push(`${colRef} = ${val ? 'TRUE' : 'FALSE'}`);
    } else {
      parts.push(`${colRef} = "${String(val)}"`);
    }
  }
  return parts.join(' && ');
}

export async function getRowBy(
  tableName: string,
  where: Record<string, unknown>
): Promise<Record<string, unknown> | null> {
  const filterExpr = buildFilterExpr(tableName, where);
  const dax = `EVALUATE FILTER('${tableName}', ${filterExpr})`;
  const res = await client.executeDaxQuery(dax);
  return res.success && res.data.length ? (res.data[0] as Record<string, unknown>) : null;
}

// Uso:
const row = await getRowBy('Sales', { OrderId: 123 });
console.log(row);

Alternativa equivalente con método del cliente:

const res = await client.queryTableById('Sales', 'OrderId', 123, 1);
const row = res.success && res.data.length ? res.data[0] : null;

Desarrollo

npm run build        # compila a dist/
npm run dev          # modo watch

Notas

  • Este paquete no expone executeMultipleQueries; usa queryTables y/o executeDaxQueries.
  • Asegúrate de otorgar permisos adecuados al Service Principal (consent y acceso al workspace/dataset). "Amount": 200.00, "Date": "2024-01-16" } ], "columns": ["ProductName", "Amount", "Date"], "rowCount": 2, "executionTime": 245 }

## Error Handling

The client provides detailed error information:

```typescript
try {
  const result = await client.queryTable('NonExistentTable');
} catch (error) {
  if (error instanceof PowerBIError) {
    console.error('Power BI Error:', error.message);
    console.error('Error Code:', error.code);
    console.error('Details:', error.details);
  }
}

Environment Variables

For security, use environment variables for configuration:

# .env file
AZURE_TENANT_ID=your-tenant-id
AZURE_CLIENT_ID=your-client-id
AZURE_CLIENT_SECRET=your-client-secret
POWERBI_GROUP_ID=your-group-id
POWERBI_DATASET_ID=your-dataset-id

Requirements

  • Node.js 14 or higher
  • Valid Azure AD application with Power BI API permissions
  • Access to Power BI Premium or Pro workspace

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

For issues and questions, please open an issue on GitHub.