Skip to content

Commit

Permalink
feat: try analytics with mongo
Browse files Browse the repository at this point in the history
  • Loading branch information
sznowicki committed Dec 22, 2023
1 parent cd158b9 commit a485b07
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
2 changes: 2 additions & 0 deletions functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -70,6 +71,7 @@ export const onRequestGet = async (context) => {
expirationTtl: 86400, // 24h
}
);
await trackQuery(context.env, { q, hasResults });
}
const view = {
...viewDefaults,
Expand Down
26 changes: 25 additions & 1 deletion lib/mongo.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?? [];
Expand Down Expand Up @@ -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`);
};

0 comments on commit a485b07

Please sign in to comment.