-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathprotocols.ts
182 lines (154 loc) · 5.02 KB
/
protocols.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
'use server';
import { Prisma } from '@prisma/client';
import { safeRevalidateTag } from 'lib/cache';
import { hash } from 'ohash';
import { type z } from 'zod';
import { getUTApi } from '~/lib/uploadthing-server-helpers';
import { protocolInsertSchema } from '~/schemas/protocol';
import { requireApiAuth } from '~/utils/auth';
import { prisma } from '~/utils/db';
import { addEvent } from './activityFeed';
// When deleting protocols we must first delete the assets associated with them
// from the cloud storage.
export async function deleteProtocols(hashes: string[]) {
await requireApiAuth();
const protocolsToBeDeleted = await prisma.protocol.findMany({
where: { hash: { in: hashes } },
select: { id: true, name: true },
});
// Select assets that are ONLY associated with the protocols to be deleted
const assetKeysToDelete = await prisma.asset.findMany({
where: {
protocols: {
every: {
id: {
in: protocolsToBeDeleted.map((p) => p.id),
},
},
},
},
select: { key: true },
});
// We put asset deletion in a separate try/catch because if it fails, we still
// want to delete the protocol.
try {
// eslint-disable-next-line no-console
console.log('deleting protocol assets...');
await deleteFilesFromUploadThing(assetKeysToDelete.map((a) => a.key));
} catch (error) {
// eslint-disable-next-line no-console
console.log('Error deleting protocol assets!', error);
}
// Delete assets in assetKeysToDelete from the database
try {
// eslint-disable-next-line no-console
console.log('deleting assets from database...');
await prisma.asset.deleteMany({
where: {
key: {
in: assetKeysToDelete.map((a) => a.key),
},
},
});
} catch (error) {
// eslint-disable-next-line no-console
console.log('Error deleting assets from database!', error);
}
try {
const deletedProtocols = await prisma.protocol.deleteMany({
where: { hash: { in: hashes } },
});
// insert an event for each protocol deleted
// eslint-disable-next-line no-console
console.log('inserting events for deleted protocols...');
const events = protocolsToBeDeleted.map((p) => {
return {
type: 'Protocol Uninstalled',
message: `Protocol "${p.name}" uninstalled`,
};
});
await prisma.events.createMany({
data: events,
});
safeRevalidateTag('activityFeed');
safeRevalidateTag('summaryStatistics');
safeRevalidateTag('getProtocols');
safeRevalidateTag('getInterviews');
safeRevalidateTag('getParticipants');
return { error: null, deletedProtocols: deletedProtocols };
} catch (error) {
// eslint-disable-next-line no-console
console.log('delete protocols error: ', error);
return {
error: 'Failed to delete protocols',
deletedProtocols: null,
};
}
}
async function deleteFilesFromUploadThing(fileKey: string | string[]) {
await requireApiAuth();
if (fileKey.length === 0) {
// eslint-disable-next-line no-console
console.log('No assets to delete');
return;
}
const utapi = await getUTApi();
const response = await utapi.deleteFiles(fileKey);
if (!response.success) {
throw new Error('Failed to delete files from uploadthing');
}
return;
}
export async function insertProtocol(
input: z.infer<typeof protocolInsertSchema>,
) {
await requireApiAuth();
const { protocol, protocolName, newAssets, existingAssetIds } =
protocolInsertSchema.parse(input);
try {
const protocolHash = hash(protocol);
await prisma.protocol.create({
data: {
hash: protocolHash,
lastModified: protocol.lastModified ?? new Date(),
name: protocolName,
schemaVersion: protocol.schemaVersion,
stages: protocol.stages,
codebook: protocol.codebook,
description: protocol.description,
assets: {
create: newAssets,
connect: existingAssetIds.map((assetId) => ({ assetId })),
},
experiments: protocol.experiments ?? Prisma.JsonNull,
},
});
void addEvent('Protocol Installed', `Protocol "${protocolName}" installed`);
safeRevalidateTag('getProtocols');
safeRevalidateTag('summaryStatistics');
return { error: null, success: true };
} catch (e) {
// Attempt to delete any assets we uploaded to storage
if (newAssets.length > 0) {
void deleteFilesFromUploadThing(newAssets.map((a) => a.key));
}
// Check for protocol already existing
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === 'P2002') {
return {
error:
'The protocol you attempted to add already exists in the database. Please remove it and try again.',
success: false,
errorDetails: e,
};
}
return {
error:
'There was an error adding your protocol to the database. See the error details for more information.',
success: false,
errorDetails: e,
};
}
throw e;
}
}