-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathadd-plaintext.ts
53 lines (44 loc) · 1.77 KB
/
add-plaintext.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
import { api } from '../../../gateway/api.server';
import { RouteMiddleware } from '../../../types/route-middleware';
import { userWithScope } from '../../../utility/user-with-scope';
import { linkHash } from './convert-linking';
export const addPlaintext: RouteMiddleware<{ id: number }, { plaintext: string }> = async context => {
const { siteId } = userWithScope(context, ['site.admin']);
const canvasId = Number(context.query.id);
const plaintext = context.requestBody.plaintext;
const siteApi = api.asUser({ siteId });
const linking = await siteApi.getCanvasLinking(canvasId);
if (!plaintext.trim()) {
context.response.status = 200;
context.response.body = { success: true, empty: true };
return;
}
const matchingPlaintexts = linking.linking.filter(singleLink => {
return singleLink.property === 'seeAlso' && singleLink.link.format === 'text/plain';
});
if (matchingPlaintexts.length) {
for (const matchingPlaintext of matchingPlaintexts) {
// Delete the existing one, and continue;
await siteApi.deleteLinkingProperty(matchingPlaintext.id);
}
}
// Create new plaintext and insert it.
const bucket = 'plaintext';
const filePath = `public/${canvasId}/${linkHash(plaintext)}.txt`;
await siteApi.saveStoragePlainText(bucket, filePath, plaintext, true);
await siteApi.addLinkToResource({
label: 'Plaintext',
link: {
id: `/public/storage/urn:madoc:site:${siteId}/${bucket}/${filePath}`,
format: 'text/plain',
label: 'Plaintext',
type: 'Text',
file_path: `public/${canvasId}/${linkHash(plaintext)}.txt`,
file_bucket: bucket,
},
resource_id: canvasId as any,
property: 'seeAlso',
});
context.response.status = 200;
context.response.body = { success: true, empty: false };
};