Edit this page

@cubejs-client/core

Vanilla JavaScript Cube.js client.

cubejs(apiToken: string | () => Promise‹string›, options: CubeJSApiOptions): CubejsApi

Creates an instance of the CubejsApi. The API entry point.

import cubejs from '@cubejs-client/core';
const cubejsApi = cubejs(
  'CUBEJS-API-TOKEN',
  { apiUrl: 'http://localhost:4000/cubejs-api/v1' }
);

You can also pass an async function or a promise that will resolve to the API token

import cubejs from '@cubejs-client/core';
const cubejsApi = cubejs(
  async () => await Auth.getJwtToken(),
  { apiUrl: 'http://localhost:4000/cubejs-api/v1' }
);

Parameters:

NameTypeDescription
apiTokenstring | () => Promise‹string›API token is used to authorize requests and determine SQL database you're accessing. In the development mode, Cube.js Backend will print the API token to the console on on startup. In case of async function authorization is updated for options.transport on each request.
optionsCubeJSApiOptions-

cubejs(options: CubeJSApiOptions): CubejsApi

Main class for accessing Cube.js API

load(query: Query, options?: LoadMethodOptions): Promise‹ResultSet

load(query: Query, options?: LoadMethodOptions, callback?: LoadMethodCallbackResultSet›): void

Fetch data for the passed query.

import cubejs from '@cubejs-client/core';
import Chart from 'chart.js';
import chartjsConfig from './toChartjsData';

const cubejsApi = cubejs('CUBEJS_TOKEN');

const resultSet = await cubejsApi.load({
 measures: ['Stories.count'],
 timeDimensions: [{
   dimension: 'Stories.time',
   dateRange: ['2015-01-01', '2015-12-31'],
   granularity: 'month'
  }]
});

const context = document.getElementById('myChart');
new Chart(context, chartjsConfig(resultSet));

Parameters:

NameTypeDescription
queryQueryQuery object
options?LoadMethodOptions-
callback?LoadMethodCallbackResultSet-

meta(options?: LoadMethodOptions): Promise‹Meta

meta(options?: LoadMethodOptions, callback?: LoadMethodCallbackMeta›): void

Get meta description of cubes available for querying.

sql(query: Query, options?: LoadMethodOptions): Promise‹SqlQuery

sql(query: Query, options?: LoadMethodOptions, callback?: LoadMethodCallbackSqlQuery›): void

Get generated SQL string for the given query.

Parameters:

NameTypeDescription
queryQueryQuery object
options?LoadMethodOptions-
callback?LoadMethodCallbackSqlQuery-

Default transport implementation.

+ new HttpTransport(options: TransportOptions): HttpTransport

request(method: string, params: any): () => Promise‹any›

Implementation of ITransport

Contains information about available cubes and it's members.

defaultTimeDimensionNameFor(memberName: string): string

filterOperatorsForMember(memberName: string, memberType: MemberType): any

membersForQuery(query: Query | null, memberType: MemberType): TCubeMeasure[] | TCubeDimension[] | TCubeMember[]

Get all members of a specific type for a given query. If empty query is provided no filtering is done based on query context and all available members are retrieved.

Parameters:

NameTypeDescription
queryQuery | nullcontext query to provide filtering of members available to add to this query
memberTypeMemberType-

resolveMember(memberName: string, memberType: MemberType): Object

Get meta information for a cube member Member meta information contains:

{
  name,
  title,
  shortTitle,
  type,
  description,
  format
}

Parameters:

NameTypeDescription
memberNamestringFully qualified member name in a form Cube.memberName
memberTypeMemberType-

stage(): string

timeElapsed(): string

Provides a convenient interface for data manipulation.

+ new ResultSet(loadResponse: LoadResponse‹T›, options?: Object): ResultSet

Creates a new instance of ResultSet based on LoadResponse data.

import cubejs, { ResultSet } from '@cubejs-client/core';

const cubejsApi = cubejs('CUBEJS_TOKEN');

const resultSet = await cubejsApi.load({
 measures: ['Stories.count'],
 timeDimensions: [{
   dimension: 'Stories.time',
   dateRange: ['2015-01-01', '2015-12-31'],
   granularity: 'month'
  }]
});

const copy = new ResultSet(resultSet.loadResponse);

annotation(): QueryAnnotations

chartPivot(pivotConfig?: PivotConfig): ChartPivotRow[]

Returns normalized query result data in the following format.

You can find the examples of using the pivotConfig here

// For the query
{
  measures: ['Stories.count'],
  timeDimensions: [{
    dimension: 'Stories.time',
    dateRange: ['2015-01-01', '2015-12-31'],
    granularity: 'month'
  }]
}

// ResultSet.chartPivot() will return
[
  { "x":"2015-01-01T00:00:00", "Stories.count": 27120, "xValues": ["2015-01-01T00:00:00"] },
  { "x":"2015-02-01T00:00:00", "Stories.count": 25861, "xValues": ["2015-02-01T00:00:00"]  },
  { "x":"2015-03-01T00:00:00", "Stories.count": 29661, "xValues": ["2015-03-01T00:00:00"]  },
  //...
]

drillDown(drillDownLocator: DrillDownLocator, pivotConfig?: PivotConfig): Query | null

Returns a measure drill down query.

Provided you have a measure with the defined drillMemebers on the Orders cube

measures: {
  count: {
    type: `count`,
    drillMembers: [Orders.status, Users.city, count],
  },
  // ...
}

Then you can use the drillDown method to see the rows that contribute to that metric

resultSet.drillDown(
  {
    xValues,
    yValues,
  },
  // you should pass the `pivotConfig` if you have used it for axes manipulation
  pivotConfig
)

the result will be a query with the required filters applied and the dimensions/measures filled out

{
  measures: ['Orders.count'],
  dimensions: ['Orders.status', 'Users.city'],
  filters: [
    // dimension and measure filters
  ],
  timeDimensions: [
    //...
  ]
}

pivot(pivotConfig?: PivotConfig): PivotRow[]

Base method for pivoting ResultSet data. Most of the times shouldn't be used directly and chartPivot or (tablePivot)[#table-pivot] should be used instead.

You can find the examples of using the pivotConfig here

// For query
{
  measures: ['Stories.count'],
  timeDimensions: [{
    dimension: 'Stories.time',
    dateRange: ['2015-01-01', '2015-03-31'],
    granularity: 'month'
  }]
}

// ResultSet.pivot({ x: ['Stories.time'], y: ['measures'] }) will return
[
  {
    xValues: ["2015-01-01T00:00:00"],
    yValuesArray: [
      [['Stories.count'], 27120]
    ]
  },
  {
    xValues: ["2015-02-01T00:00:00"],
    yValuesArray: [
      [['Stories.count'], 25861]
    ]
  },
  {
    xValues: ["2015-03-01T00:00:00"],
    yValuesArray: [
      [['Stories.count'], 29661]
    ]
  }
]

query(): Query

rawData(): T[]

serialize(): Object

Can be used to stash the ResultSet in a storage and restored later with deserialize

seriesSeriesItem›(pivotConfig?: PivotConfig): Series‹SeriesItem›[]

Returns an array of series with key, title and series data.

// For the query
{
  measures: ['Stories.count'],
  timeDimensions: [{
    dimension: 'Stories.time',
    dateRange: ['2015-01-01', '2015-12-31'],
    granularity: 'month'
  }]
}

// ResultSet.series() will return
[
  {
    key: 'Stories.count',
    title: 'Stories Count',
    series: [
      { x: '2015-01-01T00:00:00', value: 27120 },
      { x: '2015-02-01T00:00:00', value: 25861 },
      { x: '2015-03-01T00:00:00', value: 29661 },
      //...
    ],
  },
]

Type parameters:

  • SeriesItem

seriesNames(pivotConfig?: PivotConfig): SeriesNamesColumn[]

Returns an array of series objects, containing key and title parameters.

// For query
{
  measures: ['Stories.count'],
  timeDimensions: [{
    dimension: 'Stories.time',
    dateRange: ['2015-01-01', '2015-12-31'],
    granularity: 'month'
  }]
}

// ResultSet.seriesNames() will return
[
  {
    key: 'Stories.count',
    title: 'Stories Count',
    yValues: ['Stories.count'],
  },
]

tableColumns(pivotConfig?: PivotConfig): TableColumn[]

Returns an array of column definitions for tablePivot.

For example:

// For the query
{
  measures: ['Stories.count'],
  timeDimensions: [{
    dimension: 'Stories.time',
    dateRange: ['2015-01-01', '2015-12-31'],
    granularity: 'month'
  }]
}

// ResultSet.tableColumns() will return
[
  {
    key: 'Stories.time',
    dataIndex: 'Stories.time',
    title: 'Stories Time',
    shortTitle: 'Time',
    type: 'time',
    format: undefined,
  },
  {
    key: 'Stories.count',
    dataIndex: 'Stories.count',
    title: 'Stories Count',
    shortTitle: 'Count',
    type: 'count',
    format: undefined,
  },
  //...
]

In case we want to pivot the table axes

// Let's take this query as an example
{
  measures: ['Orders.count'],
  dimensions: ['Users.country', 'Users.gender']
}

// and put the dimensions on `y` axis
resultSet.tableColumns({
  x: [],
  y: ['Users.country', 'Users.gender', 'measures']
})

then tableColumns will group the table head and return

{
  key: 'Germany',
  type: 'string',
  title: 'Users Country Germany',
  shortTitle: 'Germany',
  meta: undefined,
  format: undefined,
  children: [
    {
      key: 'male',
      type: 'string',
      title: 'Users Gender male',
      shortTitle: 'male',
      meta: undefined,
      format: undefined,
      children: [
        {
          // ...
          dataIndex: 'Germany.male.Orders.count',
          shortTitle: 'Count',
        },
      ],
    },
    {
      // ...
      shortTitle: 'female',
      children: [
        {
          // ...
          dataIndex: 'Germany.female.Orders.count',
          shortTitle: 'Count',
        },
      ],
    },
  ],
},
// ...

tablePivot(pivotConfig?: PivotConfig): Array‹object›

Returns normalized query result data prepared for visualization in the table format.

You can find the examples of using the pivotConfig here

For example:

// For the query
{
  measures: ['Stories.count'],
  timeDimensions: [{
    dimension: 'Stories.time',
    dateRange: ['2015-01-01', '2015-12-31'],
    granularity: 'month'
  }]
}

// ResultSet.tablePivot() will return
[
  { "Stories.time": "2015-01-01T00:00:00", "Stories.count": 27120 },
  { "Stories.time": "2015-02-01T00:00:00", "Stories.count": 25861 },
  { "Stories.time": "2015-03-01T00:00:00", "Stories.count": 29661 },
  //...
]

static deserializeTData›(data: Object, options?: Object): ResultSet‹TData›

import { ResultSet } from '@cubejs-client/core';

const resultSet = await cubejsApi.load(query);
// You can store the result somewhere
const tmp = resultSet.serialize();

// and restore it later
const resultSet = ResultSet.deserialize(tmp);

Type parameters:

  • TData

Parameters:

NameTypeDescription
dataObjectthe result of serialize
options?Object-

static getNormalizedPivotConfig(query: Query, pivotConfig?: Partial‹PivotConfig›): PivotConfig

rawQuery(): SqlData

sql(): string

request(method: string, params: any): () => Promise‹void›

NameType
format?"currency" | "percentage"
shortTitlestring
titlestring
typestring

NameType
xstring
xValuesstring[]

NameType
keystring
series[]
titlestring

NameTypeDescription
apiUrlstringURL of your Cube.js Backend. By default, in the development environment it is http://localhost:4000/cubejs-api/v1
credentials?"omit" | "same-origin" | "include"-
headers?Record‹string, string›-
pollInterval?number-
transport?ITransportTransport implementation to use. HttpTransport will be used by default.

NameType
xValuesstring[]
yValues?string[]

NameType
dimension?string
member?string
operatorstring
values?string[]

Ƭ LoadMethodCallback: function

NameTypeDescription
progressCallback?-
mutexKey?stringKey to store the current request's MUTEX inside the mutexObj. MUTEX object is used to reject orphaned queries results when new queries are sent. For example: if two queries are sent with the same mutexKey only the last one will return results.
mutexObj?ObjectObject to store MUTEX
subscribe?booleanPass true to use continuous fetch behavior.

NameType
annotationQueryAnnotations
dataT[]
lastRefreshTimestring
queryQuery

Ƭ MemberType: "measures" | "dimensions" | "segments"

Configuration object that contains information about pivot axes and other options.

Let's apply pivotConfig and see how it affects the axes

// Example query
{
  measures: ['Orders.count'],
  dimensions: ['Users.country', 'Users.gender']
}

If we put the Users.gender dimension on y axis

resultSet.tablePivot({
  x: ['Users.country'],
  y: ['Users.gender', 'measures']
})

The resulting table will look the following way

Users Countrymale, Orders.countfemale, Orders.count
Australia327
Germany1012
US57

Now let's put the Users.country dimension on y axis instead

resultSet.tablePivot({
  x: ['Users.gender'],
  y: ['Users.country', 'measures'],
});

in this case the Users.country values will be laid out on y or columns axis

Users GenderAustralia, Orders.countGermany, Orders.countUS, Orders.count
male3105
female27127

It's also possible to put the measures on x axis. But in either case it should always be the last item of the array.

resultSet.tablePivot({
  x: ['Users.gender', 'measures'],
  y: ['Users.country'],
});
Users GendermeasuresAustraliaGermanyUS
maleOrders.count3105
femaleOrders.count27127
NameTypeDescription
fillMissingDates?boolean | nullIf true missing dates on the time dimensions will be filled with 0 for all measures.Note: the fillMissingDates option set to true will override any order applied to the query
x?string[]Dimensions to put on x or rows axis.
y?string[]Dimensions to put on y or columns axis.

NameType
xValuesArray‹string | number›
yValuesArrayArray‹[string[], number]›

NameType
stagestring
timeElapsednumber

NameType
dimensions?string[]
filters?Filter[]
limit?number
measures?string[]
offset?number
order?object
renewQuery?boolean
segments?string[]
timeDimensions?TimeDimension[]
timezone?string
ungrouped?boolean

NameType
dimensionsRecord‹string, Annotation
measuresRecord‹string, Annotation
timeDimensionsRecord‹string, Annotation

Ƭ QueryOrder: "asc" | "desc"

NameType
keystring
seriesT[]
titlestring

NameType
keystring
titlestring
yValuesstring[]

NameType
sqlSqlData

NameType
aliasNameToMemberRecord‹string, string›
cacheKeyQueriesobject
dataSourceboolean
externalboolean
sqlSqlQueryTuple

Ƭ SqlQueryTuple: [string, boolean | string | number]

Ƭ TCubeDimension: TCubeMember & object

Ƭ TCubeMeasure: TCubeMember & object

NameType
namestring
shortTitlestring
titlestring
typeTCubeMemberType

Ƭ TCubeMemberType: "time" | "number" | "string" | "boolean"

NameType
children?TableColumn[]
dataIndexstring
format?any
keystring
metaany
shortTitlestring
titlestring
typestring | number

NameType
dateRange?string | string[]
dimensionstring
granularity?TimeDimensionGranularity

Ƭ TimeDimensionGranularity: "hour" | "day" | "week" | "month" | "year"

NameTypeDescription
apiUrlstringpath to /cubejs-api/v1
authorizationstringjwt auth token
credentials?"omit" | "same-origin" | "include"-
headers?Record‹string, string›custom headers