"use strict";
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());
    });
};
exports.getFetchResponse = (fetched) => __awaiter(void 0, void 0, void 0, function* () {
    let status = fetched.status, message;
    const contentType = fetched.headers.get("content-type");
    try {
        if (contentType && contentType.indexOf("application/json") !== -1) {
            message = yield fetched.json();
        }
        else {
            message = yield fetched.text();
        }
    }
    catch (err) {
        message = "Failed to retrieve response";
    }
    return { status, message };
});
// need to make sure all ctx structures have the
// throw added to them, so that controllers don't
// throw a ctx.throw undefined when error occurs
// opts can contain, body, params and version
exports.buildCtx = (appId, emitter, opts = {}) => {
    const ctx = {
        appId,
        user: { appId },
        eventEmitter: emitter,
        throw: (code, error) => {
            throw error;
        },
    };
    if (opts.body) {
        ctx.request = { body: opts.body };
    }
    if (opts.params) {
        ctx.params = opts.params;
    }
    if (opts.version) {
        ctx.version = opts.version;
    }
    return ctx;
};
