UNPKG

stub-azure-function-context

Version:

Provides an object similar to Function Runtime's context for use in unit testing

113 lines 3.43 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 { data; index = 0; constructor(data) { this.data = Object.entries(data); } next() { try { return { value: this.data[this.index], done: this.data.length === this.index, }; } finally { this.index++; } } } class FormData { data; constructor(data) { this.data = data; } get length() { return Object.keys(this.data).length; } [Symbol.iterator]() { return new ObjectIterator(this.data); } get(name) { return this.data[name] ?? 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 = {}) { return { headers: Object.entries(data.headers || {}).reduce((headers, [key, value]) => { return { ...headers, [key.toLowerCase()]: value, }; }, {}), get(field) { return this.headers[field.toLowerCase()]; }, bufferBody: data.bufferBody ?? (data.rawBody ? Buffer.from(data.rawBody) : Buffer.from(data.body ? JSON.stringify(data.body) : [])), body: data.body ?? safeJSONParse(data.rawBody) ?? data.rawBody, method: data.method ?? 'GET', params: data.params ?? {}, query: data.query ?? {}, rawBody: data.rawBody ?? JSON.stringify(data.body), url: data.url ?? 'https://example.com/', user: data.user ?? 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'); }, ...data.params, }; } class HttpBinding { data; constructor(bindingData) { this.data = createHttpRequest(bindingData); } toTrigger() { return this.data; } toContextBinding() { return this.data; } toBindingData() { return this.data; } } exports.HttpBinding = HttpBinding; //# sourceMappingURL=http-binding.js.map