add cache for website id

pull/569/head
formica2 2021-03-24 14:48:20 +03:00
parent f8ac987bfc
commit 2f6e7786c6
3 changed files with 38 additions and 4 deletions

View File

@ -142,3 +142,5 @@ export const BROWSERS = {
'ios-webview': 'iOS (webview)', 'ios-webview': 'iOS (webview)',
searchbot: 'Searchbot', searchbot: 'Searchbot',
}; };
export const WEBSITE_ID_CACHE_TIME = 24 * 60 * 60 * 1000; // time to cache website ids(ms)

View File

@ -7,6 +7,7 @@ import {
MYSQL_DATE_FORMATS, MYSQL_DATE_FORMATS,
POSTGRESQL_DATE_FORMATS, POSTGRESQL_DATE_FORMATS,
URL_LENGTH, URL_LENGTH,
WEBSITE_ID_CACHE_TIME,
} from 'lib/constants'; } from 'lib/constants';
export function getDatabase() { 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) { export async function getWebsiteByShareId(share_id) {
return runQuery( return runQuery(
prisma.website.findUnique({ prisma.website.findUnique({

View File

@ -1,4 +1,4 @@
import { getWebsiteByUuid, getSessionByUuid, createSession } from 'lib/queries'; import { getWebsiteIDByUuidCached, getSessionByUuid, createSession } from 'lib/queries';
import { getClientInfo } from 'lib/request'; import { getClientInfo } from 'lib/request';
import { uuid, isValidUuid, parseToken } from 'lib/crypto'; 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 { 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}`); throw new Error(`Website not found: ${website_uuid}`);
} }
const { website_id } = website;
const session_uuid = uuid(website_id, hostname, ip, userAgent, os); const session_uuid = uuid(website_id, hostname, ip, userAgent, os);
let session = await getSessionByUuid(session_uuid); let session = await getSessionByUuid(session_uuid);