-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathswift.js
97 lines (89 loc) · 2.78 KB
/
swift.js
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
const fetch = require("node-fetch");
require("dotenv").config();
const { SWIFT_USER, SWIFT_PASSWORD } = process.env;
// global variables to store tokens and expiry at
let token = "";
let expiry = "";
/**
*
* @returns an auth token, either reused or a new generated one if old one expired
*/
const getAuthToken = async () => {
// reuse token if not expired
if (expiry && new Date() < new Date(expiry)) return token;
const body = {
auth: {
identity: {
methods: ["password"],
password: {
user: {
name: SWIFT_USER,
domain: { id: "default" },
password: SWIFT_PASSWORD,
},
},
},
},
};
return await fetch("https://keystone.isis.vanderbilt.edu:5000/v3/auth/tokens", {
method: "post",
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
})
.then(resp => {
token = resp.headers.get("X-Subject-Token");
return resp.json();
})
.then(data => {
expiry = data.token.expires_at;
return token;
});
};
/**
* uploads given file to the swift cluster
* @param {String} prefix the prefix to namespace the file by
* @param {String} filename original name of the file
* @param {*} stream the buffer contents of the file
* @returns status code of the request
*/
const uploadFile = async (prefix, filename, stream) => {
try {
const authToken = await getAuthToken();
const url = `https://swift.isis.vanderbilt.edu/swift/v1/test/${prefix}/${filename}`;
const data = await fetch(url, {
method: "put",
body: stream,
headers: {
"X-Auth-Token": authToken,
"X-Detect-Content-Type": true,
"X-Object-Meta-ID": prefix,
},
});
return data.status;
} catch (error) {
console.log(error);
return error;
}
};
/**
* Retrieve a file from the swift cluster
* @param {String} prefix the prefix the file is stored under
* @param {String} filename the name of the file to retrieve
* @returns file contents
*/
const getFile = async (prefix, filename) => {
console.log(`getting file ${filename} from api`);
const authToken = await getAuthToken();
const url = `https://swift.isis.vanderbilt.edu/swift/v1/test/${prefix}/${filename}`;
const data = await fetch(url, {
method: "get",
encoding: null,
headers: {
"X-Auth-Token": authToken,
},
});
console.log(data);
if (data.status === 200) return data; // file contents
throw data.status;
};
module.exports = { uploadFile, getFile };