-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject_importer.js
More file actions
142 lines (128 loc) · 4.08 KB
/
object_importer.js
File metadata and controls
142 lines (128 loc) · 4.08 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
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
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');
const { program } = require('commander');
const CONFIG_NAME = process.env.CONFIG_NAME ?? path.join(__dirname, '.config.json');
const CONFIG = JSON.parse(fs.readFileSync(CONFIG_NAME).toString())?.object_import;
async function sendRequest(endpoint, file, bucketName, keyName, token, meta) {
const contentType = mime.lookup(keyName);
const body = new FormData();
const blob = await fs.openAsBlob(file, { type: contentType });
body.append('operations', JSON.stringify({
query: `mutation Ostorage($input: IIoRestorecommerceOstorageObject!) {
ostorage {
object {
Put(input: $input) {
details {
response {
payload { url, bucket }
status { code, message }
}
operationStatus { code, message }
}
}
}
}
}`,
variables: {
input: {
bucket: `${bucketName}`,
key: `${keyName}`,
options: {
contentType: `${contentType}`
},
meta,
}
}
}));
body.append('map', JSON.stringify({ fileVar: ['variables.input.object'] }));
body.append('fileVar', blob);
const headers = {
Authorization: `Bearer ${token}`,
'Apollo-Require-Preflight': true,
};
return fetch(endpoint, { method: 'POST', body, headers });
}
function getFiles(dir, files) {
fs.readdirSync(dir).forEach(function (file) {
const subpath = path.join(dir, file);
if (fs.lstatSync(subpath).isDirectory()) {
getFiles(subpath, files);
} else {
files.push(subpath);
}
});
}
async function commandObjectImporter(args) {
console.log('Objects-Import started');
console.log(`Base directory is: \`${args.base_dir}\``);
const urns = CONFIG?.urns;
const contentList = CONFIG?.content;
if (!Array.isArray(contentList)) {
console.error('No sources (`content` parameter) defined for object directory or wrong format. Import is interrupted.');
return;
}
for (const content of contentList) {
const dir = content.dir;
const bucketName = content.bucket_name;
const scopes = content.scopes ?? [];
if (dir && bucketName) {
const fullPath = path.join(__dirname, args.base_dir, dir);
if (!fs.existsSync(fullPath)) {
console.error(`Directory: \`${fullPath}\` does not exist, skipping this directory.`);
continue;
}
console.log(`Data from \`${fullPath}\` is going to be loaded into bucket \`${bucketName}\`.`);
const files = [];
// recursively read the files from the directory and upload file
getFiles(fullPath, files);
const token = args.token;
const endpoint = args.url;
const meta = {
owners: scopes?.map(
scope => ({
id: urns.ownerIndicatoryEntity,
value: urns[scope.entity],
attributes: [
{
id: urns.ownerInstance,
value: scope.instance
}
]
})
)
}
for (const file of files) {
// To upload removing the base directory name as key
const keyName = path.join(...[content.prefix, file.substring(fullPath.length+1, file.length)].filter(f => f));
await sendRequest(
endpoint, file, bucketName, keyName, token, meta
).then(
(response) => console.log('Upload Status:', keyName, response.status, response.statusText)
);
}
}
}
}
async function main() {
program
.description('import objects')
.option(
'-u, --url <endpoint>',
'url to endpoint point',
process.env.OBJECT_IMPORT_ENTRY ?? CONFIG?.endpoint
)
.option(
'-t, --token <access_token>',
'access token to use for communications',
process.env.ACCESS_TOKEN ?? CONFIG?.access_token
)
.option(
'-b, --base_dir <base_dir>',
'base directory for object import',
process.env.OBJECT_IMPORT_BASE_DIR ?? CONFIG?.base_dir
)
.action(commandObjectImporter);
await program.parseAsync(process.argv);
}
main();