-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathpendingAssets.js
More file actions
76 lines (66 loc) · 1.74 KB
/
Copy pathpendingAssets.js
File metadata and controls
76 lines (66 loc) · 1.74 KB
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
import {
S3Client,
CopyObjectCommand,
DeleteObjectsCommand
} from '@aws-sdk/client-s3';
const s3Client = new S3Client({
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_KEY
},
region: process.env.AWS_REGION
});
function getPendingKeyFromUrl(url, userId) {
const marker = `pending/${userId}/`;
if (!url || !url.includes(marker)) {
return null;
}
const filename = url.split('?')[0].split('/').pop();
return `pending/${userId}/${filename}`;
}
export function rewritePendingFileUrls(files, userId) {
const marker = `pending/${userId}/`;
const replacement = `${userId}/`;
return files.map((file) => {
if (file.url && file.url.includes(marker)) {
return Object.assign({}, file, {
url: file.url.replace(marker, replacement)
});
}
return file;
});
}
async function moveAssetFromPending(pendingKey, userId) {
const filename = pendingKey.split('/').pop();
const destinationKey = `${userId}/${filename}`;
await s3Client.send(
new CopyObjectCommand({
Bucket: process.env.S3_BUCKET,
CopySource: `${process.env.S3_BUCKET}/${pendingKey}`,
Key: destinationKey,
ACL: 'public-read'
})
);
await s3Client.send(
new DeleteObjectsCommand({
Bucket: process.env.S3_BUCKET,
Delete: { Objects: [{ Key: pendingKey }] }
})
);
return destinationKey;
}
export async function commitPendingAssets(userId, files = []) {
const pendingKeys = [
...new Set(
files
.map((file) => getPendingKeyFromUrl(file.url, userId))
.filter(Boolean)
)
];
if (pendingKeys.length === 0) {
return [];
}
return Promise.all(
pendingKeys.map((key) => moveAssetFromPending(key, userId))
);
}