-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwidget.server.ts
72 lines (61 loc) · 1.44 KB
/
widget.server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import type { Widget } from '@prisma/client';
import type { CreateWidgetParams } from '~/schemas/widget.server';
import { prisma } from '~/utils/db.server';
import { createWidgetSchema } from '~/schemas/widget.server';
export const widgetsForUser = async (userId: string): Promise<Widget[]> => {
const widgets = await prisma.widget.findMany({
where: {
userId,
},
});
return widgets;
};
export const getWidgetForUser = async (
widgetId: Widget['id'],
userId: string,
): Promise<Widget | null> => {
try {
const widget = await prisma.widget.findFirst({
where: {
id: widgetId,
userId,
},
});
return widget;
} catch (err) {
console.log(err);
return null;
}
};
export const createWidget = async (widgetParams: CreateWidgetParams) => {
try {
const data = createWidgetSchema.parse(widgetParams);
const widget = await prisma.widget.create({
data,
});
return widget;
} catch (err) {
console.error(err);
throw err;
}
};
export const deleteWidget = async (
widgetId: Widget['id'],
userId: string,
): Promise<boolean | void> => {
try {
const widget = await getWidgetForUser(widgetId, userId);
if (!widget) {
throw new Error('Not authorized to delete this widget');
}
await prisma.widget.delete({
where: {
id: widget.id,
},
});
return true;
} catch (err) {
console.error(err);
throw err;
}
};