-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.js
185 lines (161 loc) · 5.63 KB
/
data.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
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
183
184
185
'use strict';
// S4S Discovery Data Server Providers web service
// File: data.js
const version = '20200822';
// Required modules
const EventEmitter = require('events').EventEmitter;
const sanitize = require('sanitize-filename');
const fs = require('fs');
const JSZip = require('jszip');
const util = require('./utility');
// Configuration (Kluge: config is read by all modules)
const config = require('./config');
// Setup for 'ready' event
module.exports = new EventEmitter();
// Send module 'ready' event to parent -- setTimeout() provides a "yield" so that wait is setup before emit
setTimeout(function () {
module.exports.emit('ready');
});
//---------------------------------------------------------------------------------
// The 'manifest' call (GET /data/manifest)
module.exports.manifest = function (req, res, next) {
if (req == undefined) {
// Return documentation
return {pre: {desc: 'data service', version: version},
desc: 'Create a new upload/download repository and return the Procure manifest',
return: 'The JSON object containing Procure manifest properties: name, uploadUrl, infoUrl, continueLabel, continueUrl, and successMessage'};
} else {
util.sendJson(req, res, createManifest());
return next();
}
};
// The 'upload' call (PUT /data/upload/:id)
module.exports.upload = function (req, res, next) {
if (req == undefined) {
// Return documentation
return {desc: 'Upload data for this previously defined (via manifest) :id',
params: [{name: 'id', desc: 'the upload/download id'}],
post: [{name: 'data', desc: 'the uploaded data'}],
return: '"OK" indicating successful data upload'};
} else {
saveUploadedData(req, res, req.params.id, err => {
if (err) {
res.send(400, err.message);
} else {
util.sendText(req, res, 200, 'OK');
}
});
return next();
}
};
// The 'download' call (GET /data/download/:id)
module.exports.download = function (req, res, next) {
if (req == undefined) {
// Return documentation
return {desc: 'Download data for this previously defined (via manifest) :id',
params: [{name: 'id', desc: 'the upload/download id'}],
return: 'The JSON object containing the uploaded data'};
} else {
downloadData(req, res, req.params.id, (err, data) => {
if (err) {
res.send(400, err.message);
} else {
util.sendJson(req, res, data);
}
});
return next();
}
};
//---------------------------------------------------------------------------------
// SUPPORT FUNCTIONS
// Return the JSON object containing Procure manifest properties:
// name, uploadUrl, infoUrl, continueLabel, continueUrl, and successMessage
function createManifest() {
let id = (new Date()).getTime();
return {
name: config.dataName,
uploadUrl: config.dataUploadUrl(id),
infoUrl: config.dataInfoUrl,
continueLabel: config.dataContinueLabel,
continueUrl: config.dataContinueUrl(id),
successMessage: config.dataSuccessMessage
};
}
// Write uploaded data for this previously defined (via manifest) :id
// Calls 'callback' with the err object from writeFile()
function saveUploadedData(req, res, id, callback) {
let uploadDir = `${__dirname}/${config.uploadDir}`;
fs.mkdir(uploadDir, { recursive: true }, err => {
if (err) {
callback(err);
} else {
let fileName = `${uploadDir}/${sanitize(id)}.zip`;
fs.writeFile(fileName, req.body, 'binary', err => {
callback(err);
});
}
});
}
// Download data for this previously defined (via manifest) :id
// Calls 'callback' with an err object (or null if no error) and the JSON object containing the uploaded data
function downloadData(req, res, id, callback) {
let fileName = `${__dirname}/${config.uploadDir}/${sanitize(id)}.zip`;
fs.readFile(fileName, function(err, fileContents) {
if (err) {
if (err.code === 'ENOENT') {
// Doesn't exist
callback(null, {});
} else {
callback(err, null);
}
} else {
let results = {};
let resources = {};
JSZip.loadAsync(fileContents)
.then(function (zip) {
zip.forEach((relativePath, file) => {
if (file.dir) {
// Initialize this provider
let provDirName = file.name;
let provName = provDirName.slice(0, -1);
let filesToLoad = zip.filter((r, f) => r.startsWith(provDirName) && r.endsWith('.json')); // IGNORE ATTACHMENTS
resources[provName] = {};
resources[provName].remaining = filesToLoad.length;
resources[provName].resources = [];
// Process files for this provider
filesToLoad.forEach(file => {
file.async('string')
.then(function success(content) {
// Accumulate resources for this file
let res = JSON.parse(content).entry;
if (res) {
// Files has resources
resources[provName].resources = resources[provName].resources.concat(res);
}
resources[provName].remaining--;
if (resources[provName].remaining === 0) {
// Finished this provider -- save in results
results[provName] = {
resourceType: 'Bundle',
total: resources[provName].resources.length,
entry: resources[provName].resources
}
// Check for all complete
if (Object.keys(resources).every(prov => resources[prov].remaining === 0)) {
callback(null, results);
// No longer need uploaded file
// fs.unlink(fileName, err => {
// if (err) {
// console.error(err);
// }
// });
}
}
});
})
}
});
})
}
});
}