node express | stop express server | zuora eloqua express mock | Search

The code sets up an Express web server that uses CORS, body parsing, and the getResult function to process incoming requests, and returns a JSON response with a status code of 200 if successful. The server is configured to listen on port 8181, handles error and process events, and exports a start function that returns a promise that does nothing.

Run example

npm run import -- "express rpc wrapper"

express rpc wrapper

var cors = require('cors')({origin: true});
var bodyParser = require('body-parser');
var express = require('express');
var importer = require('../Core');
var { getResult } = importer.import("get rpc permissions",
"rpc result");

var app = express();
var server = require('http').createServer(app);
app.use(bodyParser.json());    // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({// to support URL-encoded bodies
    extended: true
}));
app.use(cors);

var router = express.Router();

// TODO: ? https://en.wikipedia.org/wiki/Portmap
router.all('/rpc', (req, res) => {
    return Promise.resolve([])
        .then(() => getResult({
            command: req.body['function'] || req.query['function'],
            result: importer.interpret(req.body['function'] || req.query['function']),
            body: req.method === 'POST' ? req.body : req.query,
            circles: ['Public']
        }))
        .then(r => {
            //console.log(r);
            res.status(200).send(JSON.stringify(r, null, 4));
        })
        // TODO: object assign error?
        .catch(e => {
            const resultError = Object.getOwnPropertyNames(e).reduce((alt, key) => {
                alt[key] = e[key];
                return alt;
            }, {});
            console.log(e);
            res.status(500).send(JSON.stringify(resultError, null, 4))
        });
});

app.use(router);

// open the port
if(typeof listener !== 'undefined') {
    listener.close();
}
console.log('Listening on 0.0.0.0:8181');
var listener = server.listen(8181)
    .on('error', e => {
        debugger
        if(e.code !== 'EADDRINUSE') {
            throw e;
        }
    })
    .on('close', () => {
        debugger
    })

// shut down properly
process.on ('SIGTERM', () => {
    debugger
    listener.close()
    process.exit(0)
});
process.on ('SIGINT', () => {
    debugger
    listener.close()
    process.exit(0)
});

module.exports = function start() {
    return new Promise(resolve => {
    })
}

if(typeof $ !== 'undefined') {
    $.done();
}

What the code could have been:

// Import dependencies
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const importer = require('../Core');
const { getResult } = importer.import(['get rpc permissions', 'rpc result']);

// Initialize Express app
const app = express();

// Create an HTTP server
const server = require('http').createServer(app);

// Configure middleware
app.use(bodyParser.json());    // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // to support URL-encoded bodies
app.use(cors());

// Create a new router
const router = express.Router();

// Define a route for the RPC endpoint
router.all('/rpc', async (req, res) => {
    try {
        // Get the result from the rpcResult function
        const result = await getResult({
            command: req.body.function || req.query.function,
            result: importer.interpret(req.body.function || req.query.function),
            body: req.method === 'POST'? req.body : req.query,
            circles: ['Public']
        });

        // Send the result as JSON
        res.status(200).send(JSON.stringify(result, null, 4));
    } catch (error) {
        // Catch any errors and send a 500 response with the error details
        const errorDetails = Object.getOwnPropertyNames(error).reduce((acc, key) => {
            acc[key] = error[key];
            return acc;
        }, {});
        console.error(error);
        res.status(500).send(JSON.stringify(errorDetails, null, 4));
    }
});

// Use the router
app.use(router);

// Start the server
const listener = server.listen(8181, () => {
    console.log('Listening on 0.0.0.0:8181');
});

// Handle errors
listener.on('error', (error) => {
    if (error.code!== 'EADDRINUSE') {
        throw error;
    }
});

// Handle close event
listener.on('close', () => {
    process.exit(0);
});

// Handle SIGTERM and SIGINT signals
process.on('SIGTERM', () => {
    listener.close();
    process.exit(0);
});
process.on('SIGINT', () => {
    listener.close();
    process.exit(0);
});

module.exports = async function start() {
    // Return a promise that resolves immediately
    return Promise.resolve();
}

// Shut down properly when using the async/await syntax
async function shutdown() {
    await new Promise((resolve) => {
        listener.close(() => {
            resolve();
        });
    });
}

// Call the shutdown function when using the async/await syntax
shutdown();

// Call the done function when using the async/await syntax
if (typeof $!== 'undefined') {
    $().done();
}

Code Breakdown

Dependencies and Setup

Routing and Handling

Server and Event Handling

Exporting and Cleanup