Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Stats API fn #404

Merged
merged 12 commits into from
May 20, 2022
Merged
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

## Not released

- Implement Stats API fn [#404](https://github.com/CartoDB/carto-react/pull/404)
- Fix map filtering with CategoryWidget using boolean values [#411](https://github.com/CartoDB/carto-react/pull/411)


## 1.3

### 1.3.0-alpha.10 (2022-05-12)
Expand Down
179 changes: 179 additions & 0 deletions packages/react-api/__tests__/api/stats.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import { getStats } from '../../src/api/stats';

const TABLE_AND_QUERY_STATS = {
attribute: 'injuries',
type: 'Number',
avg: 0.44776268477826375,
sum: 4483,
min: 0,
max: 7,
quantiles: {
3: [0, 7],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice piramid 🔺 !

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's very beautiful hahaha.

4: [0, 0, 7],
5: [0, 0, 1, 7],
6: [0, 0, 0, 1, 7],
7: [0, 0, 0, 0, 1, 7],
8: [0, 0, 0, 0, 1, 1, 7],
9: [0, 0, 0, 0, 0, 1, 1, 7],
10: [0, 0, 0, 0, 0, 0, 1, 1, 7],
11: [0, 0, 0, 0, 0, 0, 1, 1, 1, 7],
12: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 7],
13: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 7],
14: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 7],
15: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 7],
16: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 7],
17: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 7],
18: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 7],
19: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 7],
20: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 7]
}
};

const mockedGetTileJson = jest.fn();

jest.mock('../../src/api/tilejson', () => ({
getTileJson: (props) => {
mockedGetTileJson(props);
return Promise.resolve({ tilestats: mockTilestats });
}
}));

const mockTilestats = {
layerCount: 1,
layers: [
{
layer: 'default',
count: 504931,
geometry: 'Point',
attributeCount: 5,
attributes: [
{
attribute: 'name',
type: 'String',
categories: [
{ category: null, frequency: 236730 },
{ category: 'Banco Santander', frequency: 2250 },
{ category: 'Caixabank', frequency: 2022 }
]
},
{
attribute: 'group_name',
type: 'String',
categories: [
{ category: 'Others', frequency: 147789 },
{ category: 'Sustenance', frequency: 94220 },
{ category: 'Transportation', frequency: 92761 }
]
}
]
}
]
};

describe('stats', () => {
describe('getStats', () => {
test('table source - should return stats', async () => {
const TABLE_TEST = {
input: {
source: {
type: 'table',
data: 'cartobq.public_account.seattle_collisions',
connection: 'carto-ps-bq-developers',
credentials: {
accessToken: '__test_api_key__',
apiBaseUrl: 'https://gcp-us-east1.api.carto.com',
apiVersion: 'v3'
}
},
column: 'injuries'
},
url: `https://gcp-us-east1.api.carto.com/v3/stats/carto-ps-bq-developers/cartobq.public_account.seattle_collisions/injuries`,
output: TABLE_AND_QUERY_STATS
};

const fetchMock = (global.fetch = jest.fn().mockImplementation(async () => {
return {
ok: true,
json: async () => TABLE_TEST.output
};
}));

const abortController = new AbortController();

const res = await getStats({ ...TABLE_TEST.input, opts: { abortController } });

expect(res).toEqual(TABLE_TEST.output);

expect(fetchMock).toBeCalledWith(TABLE_TEST.url, {
headers: {
Authorization: `Bearer ${TABLE_TEST.input.source.credentials.accessToken}`
},
signal: abortController.signal
});
});

test('query source - should return stats', async () => {
const QUERY_TEST = {
input: {
source: {
type: 'query',
data: 'SELECT * FROM `cartobq.public_account.seattle_collisions`',
connection: 'carto-ps-bq-developers',
credentials: {
accessToken: '__test_api_key__',
apiBaseUrl: 'https://gcp-us-east1.api.carto.com',
apiVersion: 'v3'
}
},
column: 'injuries'
},
url: `https://gcp-us-east1.api.carto.com/v3/stats/carto-ps-bq-developers/injuries?q=SELECT+*+FROM+%60cartobq.public_account.seattle_collisions%60`,
output: TABLE_AND_QUERY_STATS
};

const fetchMock = (global.fetch = jest.fn().mockImplementation(async () => {
return {
ok: true,
json: async () => QUERY_TEST.output
};
}));

const abortController = new AbortController();

const res = await getStats({ ...QUERY_TEST.input, opts: { abortController } });

expect(res).toEqual(QUERY_TEST.output);

expect(fetchMock).toBeCalledWith(QUERY_TEST.url, {
headers: {
Authorization: `Bearer ${QUERY_TEST.input.source.credentials.accessToken}`
},
signal: abortController.signal
});
});

test('tileset source - should return stats', async () => {
const TILESET_TEST = {
input: {
source: {
type: 'tileset',
data: 'cartobq.public_account.pois',
connection: 'carto-ps-bq-developers',
credentials: {
accessToken: '__test_api_key__',
apiBaseUrl: 'https://gcp-us-east1.api.carto.com',
apiVersion: 'v3'
}
},
column: 'name'
},
output: mockTilestats.layers[0].attributes[0]
};

const res = await getStats(TILESET_TEST.input);

expect(res).toEqual(TILESET_TEST.output);
expect(mockedGetTileJson).toBeCalledWith({ source: TILESET_TEST.input.source });
});
});
});
53 changes: 53 additions & 0 deletions packages/react-api/__tests__/api/tilejson.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { getTileJson } from '../../src/api/tilejson';
import { MAP_TYPES, API_VERSIONS } from '@deck.gl/carto';

const mockedFetchLayerData = jest.fn();

jest.mock('@deck.gl/carto', () => ({
...jest.requireActual('@deck.gl/carto'),
fetchLayerData: (props) => {
mockedFetchLayerData(props);
return Promise.resolve({
data: {},
format: 'tilejson'
});
}
}));

const TEST_CONNECTION = '__test_connection__';
const TEST_TILESET = '__test_tileset__';
const TEST_API_KEY = '__test_api_key__';

describe('tilejson', () => {
describe('getTileJson', () => {
test('should return a tilejson', async () => {
const source = {
type: MAP_TYPES.TILESET,
data: TEST_TILESET,
connection: TEST_CONNECTION,
credentials: {
accessToken: TEST_API_KEY,
apiVersion: API_VERSIONS.V3,
apiBaseUrl: 'https://gcp-us-east1.api.carto.com'
}
};

const tilejson = await getTileJson({ source });

expect(mockedFetchLayerData).toBeCalledWith({
clientId: 'carto-for-react',
connection: '__test_connection__',
credentials: {
accessToken: '__test_api_key__',
apiBaseUrl: 'https://gcp-us-east1.api.carto.com',
apiVersion: 'v3'
},
format: 'tilejson',
source: '__test_tileset__',
type: 'tileset'
});

expect(tilejson).toBeDefined();
});
});
});
39 changes: 38 additions & 1 deletion packages/react-api/src/api/common.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* Return more descriptive error from API
*/
export function dealWithApiError({ credentials, response, data }) {
export function dealWithApiError({ response, data }) {
switch (response.status) {
case 401:
throw new Error('Unauthorized access. Invalid credentials');
Expand All @@ -11,3 +11,40 @@ export function dealWithApiError({ credentials, response, data }) {
throw new Error(`${JSON.stringify(data?.hint || data.error?.[0])}`);
}
}

export function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}

export function checkCredentials(credentials) {
if (!credentials || !credentials.apiBaseUrl || !credentials.accessToken) {
throw new Error('Missing or bad credentials provided');
}
}

export async function makeCall({ url, credentials, opts }) {
let response;
let data;
try {
response = await fetch(url.toString(), {
headers: {
Authorization: `Bearer ${credentials.accessToken}`
},
signal: opts?.abortController?.signal,
...opts?.otherOptions
});
data = await response.json();
} catch (error) {
if (error.name === 'AbortError') throw error;

throw new Error(`Failed request: ${error}`);
}

if (!response.ok) {
dealWithApiError({ response, data });
}

return data;
}
28 changes: 4 additions & 24 deletions packages/react-api/src/api/lds.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { dealWithApiError } from './common';
import { checkCredentials, makeCall } from './common';

/**
* Execute a LDS geocoding service geocode request.
Expand All @@ -13,9 +13,8 @@ import { dealWithApiError } from './common';
* @param { Object= } props.opts - Additional options for the HTTP request
*/
export async function ldsGeocode({ credentials, address, country, limit, opts }) {
if (!credentials || !credentials.apiBaseUrl || !credentials.accessToken) {
throw new Error('ldsGeocode: Missing or bad credentials provided');
}
checkCredentials(credentials);

if (!address) {
throw new Error('ldsGeocode: No address provided');
}
Expand All @@ -29,30 +28,11 @@ export async function ldsGeocode({ credentials, address, country, limit, opts })
url.searchParams.set('limit', String(limit));
}

const { abortController, ...otherOptions } = opts || {};

let response;
let data;
try {
response = await fetch(url.toString(), {
headers: {
Authorization: `Bearer ${credentials.accessToken}`
},
signal: abortController?.signal,
...otherOptions
});
data = await response.json();
} catch (error) {
if (error.name === 'AbortError') throw error;
let data = await makeCall({ url, credentials, opts });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice refactor


throw new Error(`Failed to connect to LDS API: ${error}`);
}
if (Array.isArray(data)) {
data = data[0];
}
if (!response.ok) {
dealWithApiError({ credentials, response, data });
}

return data.value;
}
54 changes: 54 additions & 0 deletions packages/react-api/src/api/stats.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { assert, checkCredentials, makeCall } from './common';
import { MAP_TYPES, API_VERSIONS } from '@deck.gl/carto';
import { getTileJson } from './tilejson';

/**
* Execute a stats service request.
*
* @param { object } props
* @param { string } props.column - column to get stats for
* @param { object } props.source - source that owns the column
* @param { object= } props.opts - Additional options for the HTTP request
*/
export async function getStats(props) {
assert(props.source, 'getStats: missing source');
assert(props.column, 'getStats: missing column');

const { source, column, opts } = props;

checkCredentials(source.credentials);

assert(
source.credentials.apiVersion === API_VERSIONS.V3,
'Stats API is a feature only available in CARTO 3.'
);

if (source.type === MAP_TYPES.TILESET) {
const tileJson = await getTileJson({ source });
const tileStatsAttributes = tileJson.tilestats.layers[0].attributes;
const columnStats = tileStatsAttributes.find(({ attribute }) => attribute === column);
assert(columnStats, 'getStats: column not found in tileset attributes');
return columnStats;
} else {
const url = buildUrl(source, column);

return makeCall({ url, credentials: source.credentials, opts });
}
}

// Aux
function buildUrl(source, column) {
const isQuery = source.type === MAP_TYPES.QUERY;

const url = new URL(
`${source.credentials.apiBaseUrl}/v3/stats/${source.connection}/${
isQuery ? column : `${source.data}/${column}`
}`
);

if (isQuery) {
url.searchParams.set('q', source.data);
}

return url;
}
Loading