diff --git a/lib/constants.js b/lib/constants.js index 47603249..affd1a6b 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -142,3 +142,5 @@ export const BROWSERS = { 'ios-webview': 'iOS (webview)', searchbot: 'Searchbot', }; + +export const WEBSITE_ID_CACHE_TIME = 24 * 60 * 60 * 1000; // time to cache website ids(ms) diff --git a/lib/queries.js b/lib/queries.js index 5cdba372..0b735a97 100644 --- a/lib/queries.js +++ b/lib/queries.js @@ -7,6 +7,7 @@ import { MYSQL_DATE_FORMATS, POSTGRESQL_DATE_FORMATS, URL_LENGTH, + WEBSITE_ID_CACHE_TIME, } from 'lib/constants'; export function getDatabase() { @@ -92,6 +93,38 @@ export async function getWebsiteByUuid(website_uuid) { ); } +/** + * Caching website ids for WEBSITE_ID_CACHE_TIME ms + */ +const cacheWebsiteIDByUuid = {}; + +export async function getWebsiteIDByUuidCached(website_uuid) { + if (cacheWebsiteIDByUuid[website_uuid] && + (Date.now() - cacheWebsiteIDByUuid[website_uuid].timeout) <= WEBSITE_ID_CACHE_TIME) + return cacheWebsiteIDByUuid[website_uuid].website_id; + + const result = await runQuery( + prisma.website.findUnique({ + where: { + website_uuid, + }, + select: { + website_id: true + } + }), + ); + + if (!result) return result; + + const { website_id } = result; + + if (website_id) cacheWebsiteIDByUuid[website_uuid] = { + website_id, + timeout: Date.now() + } + return website_id; +} + export async function getWebsiteByShareId(share_id) { return runQuery( prisma.website.findUnique({ diff --git a/lib/session.js b/lib/session.js index 3d2fc7bc..91534fc3 100644 --- a/lib/session.js +++ b/lib/session.js @@ -1,4 +1,4 @@ -import { getWebsiteByUuid, getSessionByUuid, createSession } from 'lib/queries'; +import { getWebsiteIDByUuidCached, getSessionByUuid, createSession } from 'lib/queries'; import { getClientInfo } from 'lib/request'; import { uuid, isValidUuid, parseToken } from 'lib/crypto'; @@ -25,13 +25,12 @@ export async function getSession(req) { const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload); - const website = await getWebsiteByUuid(website_uuid); + const website_id = await getWebsiteIDByUuidCached(website_uuid); - if (!website) { + if (!website_id) { throw new Error(`Website not found: ${website_uuid}`); } - const { website_id } = website; const session_uuid = uuid(website_id, hostname, ip, userAgent, os); let session = await getSessionByUuid(session_uuid);