This commit is contained in:
Brian Cao 2022-10-06 13:35:38 -07:00
parent 5dd395918f
commit 5fd3ba3809
2 changed files with 55 additions and 113 deletions

View file

@ -1,12 +1,14 @@
import { parseToken } from 'next-basics';
import { validate } from 'uuid';
import { uuid } from 'lib/crypto';
import redis, { DELETED } from 'lib/redis';
import { getClientInfo, getJsonBody } from 'lib/request';
import { parseToken } from 'next-basics';
import { validate } from 'uuid';
import { createSession, getSessionByUuid, getWebsiteByUuid } from 'queries';
export async function getSession(req) {
const { payload } = getJsonBody(req);
const hasRedis = process.env.REDIS_URL;
const hasClickhouse = process.env.CLICKHOUSE_URL;
if (!payload) {
throw new Error('Invalid request');
@ -35,16 +37,14 @@ export async function getSession(req) {
websiteId = Number(await redis.client.get(`website:${website_uuid}`));
}
// // Check database if does not exists in Redis
// if (!websiteId) {
// const website = await getWebsiteByUuid(website_uuid);
// websiteId = website ? website.website_id : null;
// }
// Check database if does not exists in Redis
if (!websiteId) {
const website = await getWebsiteByUuid(website_uuid);
websiteId = website ? website.website_id : null;
}
if (!websiteId || websiteId === DELETED) {
throw new Error(
`Website not found: ${website_uuid} : ${process.env.REDIS_URL} : ${process.env.CLICKHOUSE_URL}`,
);
throw new Error(`Website not found: ${website_uuid}`);
}
const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload);
@ -53,17 +53,49 @@ export async function getSession(req) {
let sessionId = null;
let session = null;
session = {
session_id: sessionId,
session_uuid,
hostname,
browser,
os,
screen,
language,
country,
device,
};
if (!hasClickhouse) {
// Check if session exists
if (hasRedis) {
sessionId = Number(await redis.client.get(`session:${session_uuid}`));
}
// Check database if does not exists in Redis
if (!sessionId) {
session = await getSessionByUuid(session_uuid);
sessionId = session ? session.session_id : null;
}
if (!sessionId) {
try {
session = await createSession(websiteId, {
session_uuid,
hostname,
browser,
os,
screen,
language,
country,
device,
});
} catch (e) {
if (!e.message.toLowerCase().includes('unique constraint')) {
throw e;
}
}
}
} else {
session = {
session_id: sessionId,
session_uuid,
hostname,
browser,
os,
screen,
language,
country,
device,
};
}
return {
website_id: websiteId,