UNPKG

@sap/cli-core

Version:

Command-Line Interface (CLI) Core Module

46 lines (45 loc) 2.02 kB
import fs from "fs-extra"; import FormData from "form-data"; import path from "path"; import { get as getConfig, set as setConfig } from "../../../config/index.js"; import { get } from "../../../logger/index.js"; import { OPTION_FILE_PATH, OPTION_INPUT, X_OUTPUT_FILE_NAME, } from "../../../constants.js"; import { create as createCheckOptionsExistence } from "../checkOptionsExistence.js"; import { create as createNextHandler } from "../next.js"; import { create as createOptionsHandler } from "../options/index.js"; import { logVerbose } from "../../../logger/utils.js"; const readBodyFromFile = async () => async () => { const config = getConfig(); const filePath = config.options[OPTION_FILE_PATH.longName]; const logger = get("commands.handler.input.file"); const { debug, trace } = logger; debug("reading request body from %s", filePath); try { if (filePath.endsWith(".json")) { setConfig({ data: { type: "json", content: JSON.parse(await fs.readFile(filePath, "utf-8")), }, }); } else { const form = new FormData(); form.append("file", fs.createReadStream(filePath)); setConfig({ data: { type: "file", content: form, }, }); } const filename = path.basename(filePath); setConfig({ headers: { [X_OUTPUT_FILE_NAME]: filename } }); } catch (err) { logVerbose(logger, `Failed to read content from file ${filePath}. Does the file really exist and does it contain valid JSON?`); trace(`Failed to read content from file ${filePath}`, err); throw err; } }; export const create = () => createNextHandler("file.input.handler", createCheckOptionsExistence(OPTION_INPUT), createOptionsHandler(OPTION_FILE_PATH, { readEnv: true, readFile: true, readOptions: true }, true, true), readBodyFromFile);