@sasjs/cli
Version:
Command line interface for SASjs
265 lines (264 loc) • 14.9 kB
JavaScript
;
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 __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runSasJob = void 0;
var path_1 = __importDefault(require("path"));
var utils_1 = require("@sasjs/utils");
var types_1 = require("@sasjs/utils/types");
var utils_2 = require("../../utils");
function runSasJob(target, isLocal, sasJobLocation, dataFilePath, configFilePath, authConfig, logFile, jobPath, outputPathParam) {
return __awaiter(this, void 0, void 0, function () {
var dataJson, configJson, dataFile, configFile, sas9CredentialsError, sasjs, result;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
dataJson = null;
configJson = {};
if (!dataFilePath) return [3 /*break*/, 2];
dataJson = {};
if (dataFilePath.split('.').slice(-1)[0] !== 'json') {
throw new Error('Provided data file must be valid json.');
}
return [4 /*yield*/, (0, utils_1.readFile)((0, utils_1.getAbsolutePath)(dataFilePath, process.projectDir))];
case 1:
dataFile = _a.sent();
try {
dataJson = JSON.parse(dataFile);
}
catch (err) {
throw new Error('Provided data file must be valid json.');
}
_a.label = 2;
case 2:
if (!configFilePath) return [3 /*break*/, 4];
if (configFilePath.split('.').slice(-1)[0] !== 'json') {
throw new Error('Provided config file must be valid json.');
}
return [4 /*yield*/, (0, utils_1.readFile)((0, utils_1.getAbsolutePath)(configFilePath, process.projectDir))];
case 3:
configFile = _a.sent();
try {
configJson = JSON.parse(configFile);
}
catch (err) {
throw new Error('Provided config file must be valid json.');
}
_a.label = 4;
case 4:
if (target.serverType === types_1.ServerType.Sas9) {
if (target.authConfigSas9) {
configJson.username = target.authConfigSas9.userName;
configJson.password = target.authConfigSas9.password;
}
else {
configJson.username = process.env.SAS_USERNAME;
configJson.password = process.env.SAS_PASSWORD;
}
if (!configJson.username || !configJson.password) {
sas9CredentialsError = process.sasjsConstants.sas9CredentialsError;
throw new Error(sas9CredentialsError);
}
configJson.password = (0, utils_1.decodeFromBase64)(configJson.password);
}
sasjs = (0, utils_2.getSASjs)(target);
return [4 /*yield*/, sasjs
.request(sasJobLocation, dataJson, configJson, undefined, authConfig)
.then(function (res) { return __awaiter(_this, void 0, void 0, function () {
var output;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!((res && res.errorCode) || (res && res.error))) return [3 /*break*/, 2];
(0, utils_2.displayError)('Request finished with errors.');
return [4 /*yield*/, saveLogFile(sasjs, sasJobLocation, logFile, jobPath)];
case 1:
_a.sent();
return [2 /*return*/];
case 2:
if (res === undefined) {
process.logger.warn('WEBOUT is not present in response payload.');
}
_a.label = 3;
case 3:
output = '';
if (res === null || res === void 0 ? void 0 : res.result)
res = res.result;
// In sasjs request debug is always on, meaning the response object always contains the log
// This log goes to a seperate .log file, and should not be added to the output file (*.json)
// Therefore, we delete it now from the result object
else if (res === null || res === void 0 ? void 0 : res.log)
delete res.log;
// Sometimes res.result contains the log (eg when there is a SAS error)
// Here we make sure that the content in the output file (*.json) will be in json format
if (typeof res === 'string') {
try {
output = JSON.parse(res);
}
catch (error) {
(0, utils_2.displayError)('Error parsing response. JSON is expected.');
}
}
else {
output = res;
}
if (!!!output) return [3 /*break*/, 5];
return [4 /*yield*/, writeOutput(outputPathParam, output, sasJobLocation)];
case 4:
_a.sent();
_a.label = 5;
case 5: return [4 /*yield*/, saveLogFile(sasjs, sasJobLocation, logFile, jobPath)];
case 6:
_a.sent();
result = true;
return [2 /*return*/];
}
});
}); })
.catch(function (err) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, saveLogFile(sasjs, sasJobLocation, logFile, jobPath)];
case 1:
_a.sent();
throw err;
}
});
}); })];
case 5:
_a.sent();
return [2 /*return*/, result];
}
});
});
}
exports.runSasJob = runSasJob;
var saveLogFile = function (sasjs, sasJobLocation, logFile, jobPath) { return __awaiter(void 0, void 0, void 0, function () {
var sasRequests, currentRequestLog, logPath, timestamp, filename;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
sasRequests = sasjs.getSasRequests();
currentRequestLog = sasRequests.find(function (x) { return x.serviceLink === sasJobLocation; });
if (!(currentRequestLog && jobPath)) return [3 /*break*/, 4];
if (!!logFile) return [3 /*break*/, 2];
return [4 /*yield*/, (0, utils_2.isSASjsProject)()];
case 1:
logPath = (_a.sent())
? path_1.default.join(process.sasjsConstants.buildDestinationResultsFolder, 'requests')
: process.projectDir;
timestamp = (0, utils_1.generateTimestamp)();
filename = sasJobLocation.split('/').pop() // always use forward slash in SAS Drive
;
logFile = path_1.default.join(logPath, "".concat(filename, "-").concat(timestamp, ".log"));
_a.label = 2;
case 2: return [4 /*yield*/, (0, utils_2.saveLog)(currentRequestLog.logFile, logFile, jobPath || '', false)];
case 3:
_a.sent();
_a.label = 4;
case 4: return [2 /*return*/];
}
});
}); };
/**
* Writes output to the file
* @param outputPathParam path to output file
* @param output data to be written to output file
* @param sasJobLocation is used for output file name when outputPathParam is undefined
* @returns output path for the file created
*/
var writeOutput = function (outputPathParam, output, sasJobLocation) { return __awaiter(void 0, void 0, void 0, function () {
var outputPath, outputFilename, outputPathArr, timestamp, filename, outputString;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, (0, utils_2.isSASjsProject)()];
case 1:
outputPath = (_a.sent())
? path_1.default.join(process.sasjsConstants.buildDestinationResultsFolder, 'requests')
: process.projectDir;
if (outputPathParam && typeof outputPathParam === 'string') {
outputPathParam = path_1.default.join(process.projectDir, outputPathParam || '');
outputPathArr = outputPathParam.split(path_1.default.sep);
outputFilename = outputPathArr.pop();
outputPath = outputPathArr.join(path_1.default.sep);
}
return [4 /*yield*/, (0, utils_1.folderExists)(outputPath)];
case 2:
if (!!(_a.sent())) return [3 /*break*/, 4];
return [4 /*yield*/, (0, utils_1.createFolder)(outputPath)];
case 3:
_a.sent();
_a.label = 4;
case 4:
if (outputFilename) {
outputPath += "".concat(path_1.default.sep).concat(outputFilename);
}
else {
timestamp = (0, utils_1.generateTimestamp)();
filename = sasJobLocation.split('/').pop();
outputPath += "".concat(path_1.default.sep).concat(filename, "-").concat(timestamp, ".json");
}
outputString = '';
if (typeof output === 'object') {
try {
outputString = JSON.stringify(output, null, 2);
}
catch (error) {
(0, utils_2.displayError)(error, 'Result parsing failed.');
return [2 /*return*/];
}
}
else {
outputString = output;
}
if (!outputString) return [3 /*break*/, 6];
return [4 /*yield*/, (0, utils_1.createFile)(outputPath, outputString)];
case 5:
_a.sent();
(0, utils_2.displaySuccess)("Request finished. Output is stored at '".concat(outputPath, "'"));
return [3 /*break*/, 7];
case 6:
(0, utils_2.displayError)("There was a problem with writing output file. Data not present.");
_a.label = 7;
case 7: return [2 /*return*/];
}
});
}); };