Compare commits

...

2 commits

Author SHA1 Message Date
Francis Cao
14f5babea7
Merge pull request #3731 from Maxime-J/unique-constraint
Some checks are pending
Node.js CI / build (postgresql, 18.18, 10) (push) Waiting to run
Prevent duplicate key db errors on session creation
2025-11-11 11:13:14 -08:00
Maxime-J
14f3db550b Use raw query with on conflict in createSession 2025-11-11 10:32:31 +01:00
2 changed files with 40 additions and 36 deletions

View file

@ -146,6 +146,7 @@ export async function POST(request: Request) {
region,
city,
distinctId: id,
createdAt,
});
}

View file

@ -1,41 +1,44 @@
import { Prisma } from '@/generated/prisma/client';
import prisma from '@/lib/prisma';
export async function createSession(data: Prisma.SessionCreateInput) {
const {
id,
websiteId,
browser,
os,
device,
screen,
language,
country,
region,
city,
distinctId,
} = data;
const FUNCTION_NAME = 'createSession';
try {
return await prisma.client.session.create({
data: {
id,
websiteId,
browser,
os,
device,
screen,
language,
country,
region,
city,
distinctId,
},
});
} catch (e: any) {
if (e.message.toLowerCase().includes('unique constraint')) {
return null;
}
throw e;
}
export async function createSession(data: Prisma.SessionCreateInput) {
const { rawQuery } = prisma;
await rawQuery(
`
insert into session (
session_id,
website_id,
browser,
os,
device,
screen,
language,
country,
region,
city,
distinct_id,
created_at
)
values (
{{id}},
{{websiteId}},
{{browser}},
{{os}},
{{device}},
{{screen}},
{{language}},
{{country}},
{{region}},
{{city}},
{{distinctId}},
{{createdAt}}
)
on conflict (session_id) do nothing
`,
data,
FUNCTION_NAME,
);
}