function PlatformKnativeImpl()

in core/nodejsActionBase/platform/knative.js [369:512]


function PlatformKnativeImpl(platformFactory) {

    var http_method = {
        get: 'GET',
        post: 'POST',
        put: 'PUT',
        delete: 'DELETE',
        options: 'OPTIONS',
    };

    const DEFAULT_METHOD = [ 'POST' ];

    // Provide access to common runtime services
    var service = platformFactory.service;

    // TODO: Should we use app.WrapEndpoint()?
    this.run = function(req, res) {

        try {

            // Do not process requests with init. data if this is not a "stem" cell
            if (hasInitData(req) && !isStemCell(process.env))
                throw ("Cannot initialize a runtime with a dedicated function.");

            // If this is a dedicated, uninitialized runtime, then copy INIT data from env. into the request
            if( !isStemCell(process.env) && !service.initialized()){
                let body = req.body || {};
                body.init = createInitDataFromEnvironment(process.env);
            }

            // Different pre-processing logic based upon request data needed due Promise behavior
            if(hasInitData(req) && hasActivationData(req)){
                // Request has both Init and Run (activation) data
                preProcessRequest(req);
                // Invoke the OW "init" entrypoint
                service.initCode(req).then(function () {
                    // delete any INIT data (e.g., code, raw, etc.) from the 'value' data before calling run().
                    removeInitData(req.body);
                    // Invoke the OW "run" entrypoint
                    service.runCode(req).then(function (result) {
                        postProcessResponse(req, result, res)
                    });
                }).catch(function (error) {
                    console.error(error);
                    if (typeof error.code === "number" && typeof error.response !== "undefined") {
                        res.status(error.code).json(error.response);
                    } else {
                        console.error("[wrapEndpoint]", "invalid errored promise", JSON.stringify(error));
                        res.status(500).json({ error: "Internal error during function execution." });
                    }
                });
            } else if(hasInitData(req)){
                // Request has ONLY Init data
                preProcessRequest(req);
                // Invoke the OW "init" entrypoint
                service.initCode(req).then(function (result) {
                    res.status(result.code).send(result.response);
                }).catch(function (error) {
                    console.error(error);
                    if (typeof error.code === "number" && typeof error.response !== "undefined") {
                        res.status(error.code).json(error.response);
                    } else {
                        console.error("[wrapEndpoint]", "invalid errored promise", JSON.stringify(error));
                        res.status(500).json({ error: "Internal error during function execution." });
                    }
                });
            } else if(hasActivationData(req)){
                // Request has ONLY Run (activation) data
                preProcessRequest(req);
                // Invoke the OW "run" entrypoint
                service.runCode(req).then(function (result) {
                    postProcessResponse(req, result, res)
                }).catch(function (error) {
                    console.error(error);
                    if (typeof error.code === "number" && typeof error.response !== "undefined") {
                        res.status(error.code).json(error.response);
                    } else {
                        console.error("[wrapEndpoint]", "invalid errored promise", JSON.stringify(error));
                        res.status(500).json({ error: "Internal error during function execution." });
                    }
                });
            } else {
                preProcessRequest(req);
                // Invoke the OW "run" entrypoint
                service.runCode(req).then(function (result) {
                    postProcessResponse(req, result, res)
                }).catch(function (error) {
                    console.error(error);
                    if (typeof error.code === "number" && typeof error.response !== "undefined") {
                        res.status(error.code).json(error.response);
                    } else {
                        console.error("[wrapEndpoint]", "invalid errored promise", JSON.stringify(error));
                        res.status(500).json({ error: "Internal error during function execution." });
                    }
                });
            }
        } catch (e) {
            res.status(500).json({error: "internal error during request processing."})
        }
    };

    // TODO: the 'httpMethods' var should not alternatively store string and string[] types
    this.registerHandlers = function(app, platform) {
        var httpMethods = process.env.__OW_HTTP_METHODS;
        // default to "[post]" HTTP method if not defined
        if (typeof httpMethods === "undefined") {
            console.error("__OW_HTTP_METHODS is undefined; defaulting to '[post]' ...");
            httpMethods = DEFAULT_METHOD;
        } else {
            if (httpMethods.startsWith('[') && httpMethods.endsWith(']')) {
                httpMethods = httpMethods.substr(1, httpMethods.length);
                httpMethods = httpMethods.substr(0, httpMethods.length -1);
                httpMethods = httpMethods.split(',');
            }
        }
        // default to "[post]" HTTP method if specified methods are not valid
        if (!Array.isArray(httpMethods) || !Array.length) {
            console.error("__OW_HTTP_METHODS is undefined; defaulting to '[post]' ...");
            httpMethods = DEFAULT_METHOD;
        }

        httpMethods.forEach(function (method) {
            switch (method.toUpperCase()) {
                case http_method.get:
                    app.get('/', platform.run);
                    break;
                case http_method.post:
                    app.post('/', platform.run);
                    break;
                case http_method.put:
                    app.put('/', platform.run);
                    break;
                case http_method.delete:
                    app.delete('/', platform.run);
                    break;
                case http_method.options:
                    app.options('/', platform.run);
                    break;
                default:
                    console.error("Environment variable '__OW_HTTP_METHODS' has an unrecognized value (" + method + ").");
            }
        });
    };
}