fix: prisma update failing on multiple where clauses

This commit is contained in:
Bereket Engida
2024-10-14 21:19:24 +03:00
parent ef26279945
commit 675e774663
5 changed files with 59 additions and 7 deletions

View File

@@ -1,5 +1,6 @@
import { authMiddleware } from "better-auth/next-js";
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
export default authMiddleware({
customRedirect: async (session, request) => {

View File

@@ -84,6 +84,7 @@ export const mongodbAdapter = (mongo: Db) => {
.toArray();
const result = res[0];
if (!result) {
return null;
}
@@ -108,6 +109,7 @@ export const mongodbAdapter = (mongo: Db) => {
const { model, where, update } = data;
const wheres = whereConvertor(where);
if (where.length === 1) {
const res = await db.collection(model).findOneAndUpdate(
//@ts-expect-error
wheres,
@@ -116,8 +118,16 @@ export const mongodbAdapter = (mongo: Db) => {
},
{ returnDocument: "after" },
);
return removeMongoId(res);
}
const res = await db.collection(model).updateMany(
//@ts-expect-error
wheres,
{
$set: update,
},
);
return {};
},
async delete(data) {
const { model, where } = data;

View File

@@ -112,11 +112,16 @@ export const prismaAdapter = (
async update(data) {
const { model, where, update } = data;
const whereClause = whereConvertor(where);
if (where.length === 1) {
return await db[model].update({
where: whereClause,
data: update,
});
}
return await db[model].updateMany({
where: whereClause,
data: update,
});
},
async delete(data) {
const { model, where } = data;

View File

@@ -178,6 +178,38 @@ export async function runAdapterTest(opts: AdapterTestOptions) {
expect(res.length).toBe(1);
});
test("should update with multiple where", async () => {
await adapter.update({
model: "user",
where: [
{
field: "name",
value: user.name,
},
{
field: "email",
value: user.email,
},
],
update: {
email: "updated@email.com",
},
});
const updatedUser = await adapter.findOne<User>({
model: "user",
where: [
{
field: "email",
value: "updated@email.com",
},
],
});
expect(updatedUser).toMatchObject({
name: user.name,
email: "updated@email.com",
});
});
test("delete model", async () => {
await adapter.delete({
model: "user",

View File

@@ -5,7 +5,7 @@ import type { BetterAuthOptions } from "./options";
*/
export type Where = {
operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte"; //eq by default
value: string;
value: string | number | boolean;
field: string;
connector?: "AND" | "OR"; //AND by default
};
@@ -35,6 +35,10 @@ export interface Adapter {
};
offset?: number;
}) => Promise<T[]>;
/**
* ⚠︎ Update may not return the updated data
* if multiple where clauses are provided
*/
update: <T>(data: {
model: string;
where: Where[];