Skip to content

Commit

Permalink
Allow for async init and shutdown functions
Browse files Browse the repository at this point in the history
  • Loading branch information
jonirap committed Jul 17, 2023
1 parent 8e79130 commit 1afa4bb
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 32 deletions.
60 changes: 38 additions & 22 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const eventHandler = require('./lib/event-handler');
const Context = require('./lib/context');
const shutdown = require('death')({ uncaughtException: true });
const fastifyRawBody = require('fastify-raw-body');
const { isPromise } = require('./lib/utils');

// HTTP framework
const fastify = require('fastify');
Expand Down Expand Up @@ -41,7 +42,10 @@ async function start(func, options) {
throw new TypeError('Function must export a handle function');
}
if (typeof func.init === 'function') {
func.init();
const initRet = func.init();
if (isPromise(initRet)) {
await initRet;
}
}
if (typeof func.shutdown === 'function') {
options.shutdown = func.shutdown;
Expand Down Expand Up @@ -79,10 +83,10 @@ async function __start(func, options) {
try {
await server.listen({
port: config.port,
host: '::'
host: '::',
});
return server.server;
} catch(err) {
} catch (err) {
console.error('Error starting server', err);
process.exit(1);
}
Expand All @@ -100,12 +104,12 @@ function initializeServer(config) {
level: config.logLevel,
formatters: {
bindings: bindings => ({
pid: bindings.pid,
hostname: bindings.hostname,
node_version: process.version
})
}
}
pid: bindings.pid,
hostname: bindings.hostname,
node_version: process.version,
}),
},
},
});

if (config.includeRaw) {
Expand All @@ -118,16 +122,20 @@ function initializeServer(config) {
}

// Give the Function an opportunity to clean up before the process exits
shutdown(_ => {
shutdown(async _ => {
if (typeof config.shutdown === 'function') {
config.shutdown();
const shutdownRet = config.shutdown();
if (isPromise(shutdownRet)) {
await shutdownRet;
}
}
server.close();
process.exit(0);
});

// Add a parser for application/x-www-form-urlencoded
server.addContentTypeParser('application/x-www-form-urlencoded',
server.addContentTypeParser(
'application/x-www-form-urlencoded',
function(_, payload, done) {
var body = '';
payload.on('data', data => (body += data));
Expand All @@ -140,18 +148,23 @@ function initializeServer(config) {
}
});
payload.on('error', done);
});
}
);

// Add a parser for everything else - parse it as a buffer and
// let this framework's router handle it
server.addContentTypeParser('*', { parseAs: 'buffer' }, function(req, body, done) {
try {
done(null, body);
} catch (err) {
err.statusCode = 500;
done(err, undefined);
server.addContentTypeParser(
'*',
{ parseAs: 'buffer' },
function(req, body, done) {
try {
done(null, body);
} catch (err) {
err.statusCode = 500;
done(err, undefined);
}
}
});
);

// Initialize the invocation context
// This is passed as a parameter to the function when it's invoked
Expand Down Expand Up @@ -210,11 +223,14 @@ function readFuncYaml(fileOrDirPath) {
if (!!maybeYaml && maybeYaml.isFile()) {
try {
return yaml.load(fs.readFileSync(yamlFile, 'utf8'));
} catch(err) {
} catch (err) {
console.warn(err);
}
}
}
}

module.exports = exports = { start, defaults: { LOG_LEVEL, PORT, INCLUDE_RAW } };
module.exports = exports = {
start,
defaults: { LOG_LEVEL, PORT, INCLUDE_RAW },
};
4 changes: 2 additions & 2 deletions lib/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ import { Http2ServerRequest, Http2ServerResponse } from 'http2';
export interface Function {
// The initialization function, called before the server is started
// This function is optional and should be synchronous.
init?: () => any;
init?: () => any | Promise<any>;

// The shutdown function, called after the server is stopped
// This function is optional and should be synchronous.
shutdown?: () => any;
shutdown?: () => any | Promise<any>;

// The liveness function, called to check if the server is alive
// This function is optional and should return 200/OK if the server is alive.
Expand Down
9 changes: 9 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function isPromise(p) {
if (typeof p === 'object' && typeof p.then === 'function') {
return true;
}

return false;
}

module.exports = exports = { isPromise };
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"type": "commonjs",
"scripts": {
"lint": "eslint --ignore-path .gitignore .",
"fix-lint": "eslint --fix --ignore-path .gitignore .",
"test": "npm run test:source && npm run test:types",
"test:source": "nyc --reporter=lcovonly tape test/test*.js | colortape",
"test:types": "tsd",
Expand Down
11 changes: 3 additions & 8 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
{
"include": [
"./index.d.ts",
"./lib/**/*.ts"
],
"exclude": [
"node_modules"
]
}
"include": ["./index.d.ts", "./lib/**/*.ts"],
"exclude": ["node_modules"],
}

0 comments on commit 1afa4bb

Please sign in to comment.