-
Notifications
You must be signed in to change notification settings - Fork 16
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
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
87a1d10
Implement Stats API fn
1f6e229
Generalise common parts in lds and stats
2788086
Remove unused imports
8ada59b
Use assert
8030a00
Merge branch 'master' of github.com:CartoDB/carto-react into feature/…
55cfc6c
Implement getTileJson
dd60f8f
Support tileset stats in getStats fn
27f4f42
Merge branch 'master' of github.com:CartoDB/carto-react into feature/…
d4ee540
Add tilejson test
5bea0c0
Add stats tests
19177b1
Export as private
3a05d48
Update CHANGELOG.md
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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], | ||
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 }); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | ||
|
@@ -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'); | ||
} | ||
|
@@ -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 }); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice piramid 🔺 !
There was a problem hiding this comment.
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.