Skip to content

Commit

Permalink
Added stats command
Browse files Browse the repository at this point in the history
  • Loading branch information
onmax committed Sep 13, 2023
1 parent 6437cdd commit f151e08
Show file tree
Hide file tree
Showing 9 changed files with 135 additions and 21 deletions.
4 changes: 2 additions & 2 deletions bot/functions/get_location.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { getDbArgs } from '../util/db-args.ts'
import { LocationType } from '../types/location.ts'

export const GetLocation = DefineFunction({
callback_id: 'get_location',
callback_id: 'get_location_info',
title: 'Get location',
description: 'Gets the location given any of its params.',
source_file: 'functions/get_location.ts',
Expand All @@ -31,7 +31,7 @@ export const GetLocation = DefineFunction({
properties: {
location: {
type: LocationType,
description: 'The location',
description: 'The location instance',
},
},
required: ['location'],
Expand Down
45 changes: 45 additions & 0 deletions bot/functions/get_stats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* eslint-disable no-console */

import {
DefineFunction,
Schema,
SlackFunction,
} from 'https://deno.land/x/[email protected]/mod.ts'
import { getStats } from '../../database/getters.ts'
import { getDbAuthArgs } from '../util/db-args.ts'

export const GetStats = DefineFunction({
callback_id: 'get_stats',
title: 'Get stats',
description: 'Gets the stats from the database',
source_file: 'functions/get_stats.ts',
input_parameters: {
properties: {
environment: {
type: Schema.types.string,
enum: ['Test', 'Production'],
},
},
required: ['environment'],
},
output_parameters: {
properties: {
stats: {
type: Schema.types.object,
description: 'The stats from the database as JSON',
},
},
required: ['stats'],
},
})

export default SlackFunction(
GetStats,
async ({ inputs, env }) => {
const res = await getStats(getDbAuthArgs(env, inputs.environment === 'Test'))
console.log(`Fetched stats ${JSON.stringify(res)}`)
return !res || typeof res === 'string'
? { error: JSON.stringify(res) }
: { outputs: { stats: res } }
},
)
15 changes: 15 additions & 0 deletions bot/functions/send_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export const SendContext = DefineFunction({
type: LocationType,
description: 'Name of the location',
},
stats: {
type: Schema.types.object,
description: 'Stats of the database',
},
reviewer: {
type: Schema.slack.types.user_id,
},
Expand All @@ -31,6 +35,7 @@ export const SendContext = DefineFunction({
'location_deleted',
'location_added',
'location_info',
'stats',
'info',
],
},
Expand Down Expand Up @@ -79,6 +84,16 @@ export default SlackFunction(
: env.CRYPTO_MAP_DOMAIN,
})
break
case 'stats':
text = `:cryptomap: Crypto Map Statistics :bar_chart:
Message triggered by <@${inputs.reviewer!}>.
\`\`\`
${JSON.stringify(inputs.stats, null, 2)}
\`\`\`
`
break
case 'info':
text = `:cryptomap: Crypto Map Bot Help :cryptomap:
Expand Down
7 changes: 3 additions & 4 deletions bot/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import CreateAddLocationPlaceIdWorkflow from './workflows/add_location_place_id.
import CreateAddLocationRawWorkflow from './workflows/add_location_manually.ts'
import DeleteLocationWorkflow from './workflows/delete_location.ts'
import GetLocationInfoWorkflow from './workflows/get_location_info.ts'
import HandleCandidateWorkflow from './workflows/handle_candidate.ts'
import GetStatsWorkflow from './workflows/get_stats_info.ts'
import HandleIssueWorkflow from './workflows/handle_issue.ts'
import HandleCandidateWorkflow from './workflows/handle_candidate.ts'
import ShowHelpWorkflow from './workflows/show_help.ts'

export default Manifest({
Expand All @@ -15,15 +16,13 @@ export default Manifest({
workflows: [
CreateAddLocationPlaceIdWorkflow,
CreateAddLocationRawWorkflow,
GetStatsWorkflow,
DeleteLocationWorkflow,
GetLocationInfoWorkflow,
HandleCandidateWorkflow,
HandleIssueWorkflow,
ShowHelpWorkflow,
],
// functions: [
// CreateLocationWithPlaceId, CreateRawLocation, DeleteLocation, GetLocation, HandleCandidateMessage, HandleIssueMessage, SendContext, UpdateContextMessage, VerifyCaptcha,
// ],
outgoingDomains: [
'www.google.com',
'mycbdmurjytbdahjljoh.supabase.co',
Expand Down
4 changes: 1 addition & 3 deletions bot/triggers/create_get_location_info_shortcut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import {
} from 'https://deno.land/x/[email protected]/mod.ts'
import GetLocationInfoWorkflow from '../workflows/get_location_info.ts'

const createDeleteLocationShortcut: Trigger<
typeof GetLocationInfoWorkflow.definition
> = {
const createDeleteLocationShortcut: Trigger<typeof GetLocationInfoWorkflow.definition> = {
type: TriggerTypes.Shortcut,
name: 'Get Location info',
description: 'Get Location info with a uuid',
Expand Down
20 changes: 20 additions & 0 deletions bot/triggers/create_get_stats_shortcut.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import type { Trigger } from 'https://deno.land/x/[email protected]/types.ts'
import {
TriggerContextData,
TriggerTypes,
} from 'https://deno.land/x/[email protected]/mod.ts'
import GetStatsInfoWorkflow from '../workflows/get_stats_info.ts'

const createDeleteLocationShortcut: Trigger<typeof GetStatsInfoWorkflow.definition> = {
type: TriggerTypes.Shortcut,
name: 'Get Stats',
description: 'Get Stats from the database',
workflow: `#/workflows/${GetStatsInfoWorkflow.definition.callback_id}`,
inputs: {
interactivity: {
value: TriggerContextData.Shortcut.interactivity,
},
},
}

export default createDeleteLocationShortcut
37 changes: 37 additions & 0 deletions bot/workflows/get_stats_info.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import {
DefineWorkflow,
Schema,
} from 'https://deno.land/x/[email protected]/mod.ts'
import { SendContext } from '../functions/send_context.ts'
import { GetStats } from '../functions/get_stats.ts'

const GetStatsWorkflow = DefineWorkflow({
callback_id: 'get_stats_wf',
title: 'Get stats',
description: 'Get stats from the database',
input_parameters: {
properties: {
interactivity: {
type: Schema.slack.types.interactivity,
},
},
required: ['interactivity'],
},
})

const statsStep = GetStatsWorkflow.addStep(
GetStats,
{ environment: 'Production' },
)

GetStatsWorkflow.addStep(
SendContext,
{
stats: statsStep.outputs.stats,
environment: 'Production',
reviewer: GetStatsWorkflow.inputs.interactivity.interactor.id,
type: 'stats',
},
)

export default GetStatsWorkflow
2 changes: 1 addition & 1 deletion database/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export async function fetchDb<T, FnName extends DbReadFunction | DbWriteFunction
const body = isWriteOperation ? parameters : undefined

const requiredHeaders = { ...HEADERS, apikey }
const headers = isWriteOperation ? { ...requiredHeaders, Authorization: `Bearer ${token}` } : requiredHeaders
const headers = token ? { ...requiredHeaders, Authorization: `Bearer ${token}` } : requiredHeaders

/* eslint-disable no-console */
console.group(`🔍 Database ${method} "${url.pathname.split('/').pop()}${url.search}"`)
Expand Down
22 changes: 11 additions & 11 deletions database/getters.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { BoundingBox, ComputedClusterSet, DatabaseArgs, DatabaseStatistics, Location, Suggestion } from '../types/index.ts'
import type { BoundingBox, ComputedClusterSet, DatabaseArgs, DatabaseAuthArgs, DatabaseStatistics, Location, Suggestion } from '../types/index.ts'
import { Category, Currency, DbReadFunction, Provider } from '../types/index.ts'
import { fetchDb } from './fetch.ts'

Expand All @@ -17,28 +17,28 @@ export async function getLocations(dbArgs: DatabaseArgs, bbox: BoundingBox, pars
return locations.map(parseLocations)
}

export async function getLocation({ apikey, url: baseUrl }: DatabaseArgs, uuid: string, parseLocation: (l: Location) => Location): Promise<Location | undefined> {
export async function getLocation(dbArgs: DatabaseArgs, uuid: string, parseLocation: (l: Location) => Location): Promise<Location | undefined> {
const params = new URLSearchParams()
params.append('location_uuid', uuid)
const location = await fetchDb<Location>(DbReadFunction.GetLocation, { apikey, url: baseUrl }, params.toString())
const location = await fetchDb<Location>(DbReadFunction.GetLocation, dbArgs, params.toString())
if (!location) {
console.warn(`Location ${uuid} not found`)
return undefined
}
return parseLocation(location)
}

export async function searchLocations({ apikey, url: baseUrl }: DatabaseArgs, query: string) {
export async function searchLocations(dbArgs: DatabaseArgs, query: string) {
const params = new URLSearchParams()
params.append('p_query', query)
return await fetchDb<Omit<Suggestion, 'type'>[]>(DbReadFunction.SearchLocations, { apikey, url: baseUrl }, params.toString()) ?? []
return await fetchDb<Omit<Suggestion, 'type'>[]>(DbReadFunction.SearchLocations, dbArgs, params.toString()) ?? []
}

export async function getClusters({ apikey, url: baseUrl }: DatabaseArgs, bbox: BoundingBox, zoom: number, parseLocation: (l: Location) => Location = l => l): Promise<ComputedClusterSet> {
export async function getClusters(dbArgs: DatabaseArgs, bbox: BoundingBox, zoom: number, parseLocation: (l: Location) => Location = l => l): Promise<ComputedClusterSet> {
const params = new URLSearchParams()
Object.entries(bbox).forEach(([key, value]) => params.append(key.toLocaleLowerCase(), value.toString()))
params.append('zoom_level', zoom.toString())
const res = await fetchDb<ComputedClusterSet>(DbReadFunction.GetLocationsClustersSet, { apikey, url: baseUrl }, params.toString())
const res = await fetchDb<ComputedClusterSet>(DbReadFunction.GetLocationsClustersSet, dbArgs, params.toString())
return {
clusters: res?.clusters ?? [],
singles: res?.singles.map(parseLocation) ?? [],
Expand All @@ -49,10 +49,10 @@ export async function getClusters({ apikey, url: baseUrl }: DatabaseArgs, bbox:
* The maximum zoom level at which the clusters are computed in the database.
* If the user zooms in more than this, the clusters will be computed in the client.
*/
export async function getClusterMaxZoom({ apikey, url: baseUrl }: DatabaseArgs): Promise<number> {
return await fetchDb<number>(DbReadFunction.GetMaxZoom, { apikey, url: baseUrl }) ?? -1 // FIXME: Show error to user instead of using -1
export async function getClusterMaxZoom(dbArgs: DatabaseArgs): Promise<number> {
return await fetchDb<number>(DbReadFunction.GetMaxZoom, dbArgs) ?? -1 // FIXME: Show error to user instead of using -1
}

export async function getStats({ apikey, url: baseUrl }: DatabaseArgs): Promise<DatabaseStatistics | undefined> {
return await fetchDb<DatabaseStatistics>(DbReadFunction.GetStats, { apikey, url: baseUrl })
export async function getStats(dbArgs: DatabaseAuthArgs): Promise<DatabaseStatistics | undefined> {
return await fetchDb<DatabaseStatistics>(DbReadFunction.GetStats, dbArgs)
}

0 comments on commit f151e08

Please sign in to comment.