UNPKG

zcatalyst-cli

Version:

Command Line Tool for CATALYST

92 lines (80 loc) 2.44 kB
'use strict'; import * as path from 'path'; import * as fs from 'fs'; import { pathToFileURL } from 'url'; const args = process.argv.slice(2); const target = JSON.parse(args[0]); const userData = JSON.parse(args[1]); const projectJson = JSON.parse(args[2]); const authJson = JSON.parse(args[3]); const buildDir = JSON.parse(args[4]); const requestFile = path.join(buildDir, '.catalyst', 'user_req_body'); const responseFile = path.join(buildDir, '.catalyst', 'user_res_body'); const metaFile = path.join(buildDir, '.catalyst', 'user_meta.json'); const writeToFile = (resp, status) => { fs.writeFileSync(responseFile, resp); fs.writeFileSync(metaFile, JSON.stringify({ response: { statusCode: status } })); }; let body = {}; if (fs.existsSync(requestFile)) { const content = fs.readFileSync(requestFile); try { body = JSON.parse(content.toString()); } catch (err) { body = {}; } } /** * execution timeout 15 minutes */ const timeout = 15 * 60 * 1000; const endTime = timeout + Date.now(); // exit on timeout process.env.DEBUG === 'false' && setTimeout(() => { writeToFile('TIMEOUT', 408); process.exit(0); }, timeout); const context = { catalystHeaders: Object.assign(projectJson, authJson), getMaxExecutionTimeMs: () => timeout, getRemainingExecutionTimeMs: () => endTime - Date.now(), closeWithSuccess: () => { writeToFile('SUCCESS', 200); process.exit(0); }, closeWithFailure: () => { writeToFile('FAILURE', 530); process.exit(0); } }; const cronReq = { getCronParam: (KEY) => userData.data[KEY] || body[KEY], getAllCronParams: () => (Object.keys(userData.data).length > 0 ? userData.data : body), getRemainingExecutionCount: () => userData.remaining_count || -1, getCronDetails: () => userData.cron_details || null, getProjectDetails: () => userData.project_details || projectJson }; import(pathToFileURL(target.index)) .then((module) => { try { if (!('default' in module)) { throw new Error('Could not find any default export'); } if (typeof module.default !== 'function') { throw new Error('The default export is not a function'); } module.default(cronReq, context); } catch (e) { // eslint-disable-next-line no-console console.error(e); writeToFile('CODE_EXCEPTION', 532); process.exit(0); } }) .catch((e) => { // eslint-disable-next-line no-console console.error(e); writeToFile('INTERNAL_SERVER_ERROR', 500); process.exit(0); });