UNPKG

@naktibalda/stub-azure-function-context

Version:
104 lines 3.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpBinding = void 0; const content_type_1 = require("content-type"); const url_1 = require("url"); function safeJSONParse(text, reviver) { try { return JSON.parse(text, reviver); } catch (e) { return undefined; } } class ObjectIterator { constructor(data) { this.index = 0; this.data = Object.entries(data); } next() { try { return { value: this.data[this.index], done: this.data.length === this.index, }; } finally { this.index++; } } } class FormData { constructor(data) { this.data = data; } get length() { return Object.keys(this.data).length; } [Symbol.iterator]() { return new ObjectIterator(this.data); } get(name) { var _a; return (_a = this.data[name]) !== null && _a !== void 0 ? _a : null; } getAll(name) { if (this.has(name)) { return [this.get(name)]; } return []; } has(name) { return Object.prototype.hasOwnProperty.call(this.data, name); } } function createHttpRequest(data = {}) { var _a, _b, _c, _d, _e, _f, _g, _h; return { headers: Object.entries(data.headers || {}).reduce((headers, [key, value]) => { return { ...headers, [key.toLowerCase()]: value, }; }, {}), body: (_b = (_a = data.body) !== null && _a !== void 0 ? _a : safeJSONParse(data.rawBody)) !== null && _b !== void 0 ? _b : data.rawBody, method: (_c = data.method) !== null && _c !== void 0 ? _c : 'GET', params: (_d = data.params) !== null && _d !== void 0 ? _d : {}, query: (_e = data.query) !== null && _e !== void 0 ? _e : {}, rawBody: (_f = data.rawBody) !== null && _f !== void 0 ? _f : JSON.stringify(data.body), url: (_g = data.url) !== null && _g !== void 0 ? _g : 'https://example.com/', user: (_h = data.user) !== null && _h !== void 0 ? _h : null, parseFormBody() { if (!this.headers['content-type']) { throw new Error('No content-type specified, cannot parse form body'); } const contentType = (0, content_type_1.parse)(this.headers['content-type']); if (['multipart/form-data', 'application/x-www-form-urlencoded'].includes(contentType.type)) { throw new Error('content-type must be one of multipart/form-data or application/x-www-form-urlencoded'); } if (contentType.type === 'application/x-www-form-urlencoded') { const data = new url_1.URL(this.rawBody); return new FormData(Object.entries(data.searchParams).reduce((formData, [name, value]) => { return { ...formData, [name]: { value: Buffer.from(value) }, }; }, {})); } throw new Error('multipart/form-data support not yet implemented'); }, }; } class HttpBinding { constructor(bindingData) { this.data = createHttpRequest(bindingData); } toTrigger() { return this.data; } toContextBinding() { return this.data; } } exports.HttpBinding = HttpBinding; //# sourceMappingURL=http-binding.js.map