@orvium/orvium-tools
Version:
Set of tools to interact with Orvium API
161 lines (160 loc) • 7.22 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.exportDeposit = exportDeposit;
const axios_1 = __importDefault(require("axios"));
const fs = __importStar(require("fs")); // To save the ZIP file locally
const path = __importStar(require("path"));
const dotenv_1 = __importDefault(require("dotenv"));
const archiver_1 = __importDefault(require("archiver"));
/**
* Load and prepare environment variables
*/
dotenv_1.default.config();
//Obtain the api key from the env variable
const API_KEY = process.env.API_KEY;
const API_KEY_USER = process.env.API_KEY_USER;
// Function to retrieve a deposit by ID
function getDepositById(depositId) {
return __awaiter(this, void 0, void 0, function* () {
const apiUrl = `${process.env.API_URL}/deposits/${depositId}`;
try {
// Make the GET request to retrieve deposit details
const response = yield axios_1.default.get(apiUrl, {
headers: {
'x-api-key': API_KEY,
'x-api-key-user': API_KEY_USER,
},
});
// Return the deposit details from the response
return response.data;
}
catch (error) {
if (error.response) {
console.error(`Error: ${error.response.status} - ${error.response.data}`);
}
else {
console.error('Error:', error.message);
}
return null;
}
});
}
// Function to get a signed URL for a specific file in the deposit and download the file
function downloadDepositFile(depositId, filename, downloadPath) {
return __awaiter(this, void 0, void 0, function* () {
const fileUrl = `${process.env.API_URL}/deposits/${depositId}/files/${filename}`;
try {
// Request the signed URL for the file
const response = yield axios_1.default.get(fileUrl, {
headers: {
'x-api-key': API_KEY,
'x-api-key-user': API_KEY_USER,
},
maxRedirects: 0, // Prevent axios from following the redirect
validateStatus: (status) => status === 302, // Only accept status 302 for redirection
});
// Get the signed URL from the location header
const signedUrl = response.headers['location'];
if (!signedUrl) {
throw new Error('Signed URL not found in response headers');
}
// Download the file using the signed URL
const fileResponse = yield axios_1.default.get(signedUrl, { responseType: 'stream' });
const filePath = path.join(downloadPath, filename);
const writer = fs.createWriteStream(filePath);
fileResponse.data.pipe(writer);
yield new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
}
catch (error) {
if (error.response) {
console.error(`Error: ${error.response.status} - ${error.response.data}`);
}
else {
console.error('Error:', error.message);
}
}
});
}
function exportDeposit(depositId, downloadPath) {
return __awaiter(this, void 0, void 0, function* () {
const depositPopulated = yield getDepositById(depositId);
if (!depositPopulated) {
throw new Error('depositPopulated cannot be null');
}
const deposit = {
title: depositPopulated.title,
abstract: depositPopulated.abstract,
disciplines: depositPopulated.disciplines,
authors: depositPopulated.authors.map((author) => ({
firstName: author.firstName,
lastName: author.lastName,
nickName: author.nickName || '',
email: author.email || '',
orcid: author.orcid || '',
})),
keywords: depositPopulated.keywords,
community: depositPopulated.communityPopulated.name,
manuscript: {
filename: depositPopulated.publicationFile.description,
}
};
const metadataPath = path.join(downloadPath, 'meta.json');
const manuscriptPath = path.join(downloadPath, depositPopulated.publicationFile.filename);
fs.writeFileSync(metadataPath, JSON.stringify(deposit, null, 2));
yield downloadDepositFile(depositId, depositPopulated.publicationFile.filename, downloadPath);
const zipFilePath = path.join(downloadPath, `deposit_${depositId}.zip`);
const archive = (0, archiver_1.default)('zip', { zlib: { level: 9 } });
const output = fs.createWriteStream(zipFilePath);
output.on('close', () => {
console.log(`ZIP file created successfully: ${zipFilePath}`);
});
archive.on('error', (err) => {
throw err;
});
archive.pipe(output);
archive.file(metadataPath, { name: 'meta.json' });
archive.file(manuscriptPath, { name: deposit.manuscript.filename });
yield archive.finalize();
// Eliminar archivos temporales si es necesario
fs.unlinkSync(metadataPath);
fs.unlinkSync(manuscriptPath);
});
}