From a485b0707ce199ad25bf154d3c90dca68c8b1c1c Mon Sep 17 00:00:00 2001 From: Szymon Nowicki Date: Fri, 22 Dec 2023 19:41:36 +0100 Subject: [PATCH] feat: try analytics with mongo --- functions/index.js | 2 ++ lib/mongo.js | 26 +++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/functions/index.js b/functions/index.js index 4a7f05f..dad0f2e 100644 --- a/functions/index.js +++ b/functions/index.js @@ -5,6 +5,7 @@ import classNames from 'html-classnames'; import {getDefaultViewData} from '../lib/view.js'; import {emitPageView} from '../lib/plausible.js'; import {parseQuery} from '../lib/parseQuery.js'; +import {trackQuery} from '../lib/mongo.js'; export const onRequestGet = async (context) => { const { request, env } = context; @@ -70,6 +71,7 @@ export const onRequestGet = async (context) => { expirationTtl: 86400, // 24h } ); + await trackQuery(context.env, { q, hasResults }); } const view = { ...viewDefaults, diff --git a/lib/mongo.js b/lib/mongo.js index c79ea50..b2e6570 100644 --- a/lib/mongo.js +++ b/lib/mongo.js @@ -22,7 +22,7 @@ export const getIndexStats = async (envs) => { collection: envs.ATLAS_COLLECTION, database: envs.ATLAS_DB, dataSource: envs.ATLAS_SOURCE, - projection: { url: 1, lastCrawledAt: 1, index: 1} + projection: {url: 1, lastCrawledAt: 1, index: 1} }); return response?.documents ?? []; @@ -50,3 +50,27 @@ export const getUnchecked = async (envs) => { return response?.documents?.[0]?.count ?? null; }; + +export const trackQuery = async (envs, {q, hasResults}) => { + const d = Date.now(); + await callMongo(envs, 'updateOne', { + collection: 'queries', + database: envs.ATLAS_DB, + dataSource: envs.ATLAS_SOURCE, + filter: { + q, + }, + update: { + $inc: { + used: 1, + }, + $set: { + q, + hasResults, + lastUse: Date.now() + } + }, + upsert: true, + }); + console.log(`Analytics via mongo took ${Date.now() - d}ms`); +};