-
Notifications
You must be signed in to change notification settings - Fork 44
Description
Sample Usage
This has been updated to reflect the final design
import { registerHook } from '@azure/functions-core';
registerHook('preInvocation', (context: PreInvocationContext) => {
// can completely change the inputs passed to a user's function
context.inputs = ['hello'];
// can write to `context.hookData` and read the value in a postInvocationHook
context.hookData.value = 1;
// can write to the _invocation_ context passed to a user's function
context.invocationContext.dataForInvoc = 2;
});
const disposable = registerHook('postInvocation', (context: PostInvocationContext) => {
// can read data from `context.hookData` set in the preInvocationHook
if (context.hookData.value === 1) {
}
// can modify the error thrown by the function
if (context.error) {
context.error = new Error(`Add a prefix to error text: ${context.error.message}`);
}
// can completely change the result of a function
context.result = 'world';
});
disposable.dispose(); // Can stop the hook from executing in the future
NOTE: If you want to use hooks with esm, you have to import registerHook
slightly differently:
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const { registerHook } = require('@azure/functions-core');
// The rest works the same as above
registerHook('preInvocation', async (context) => {
});
Background
Basically, users should be able to register a hook that runs a piece of code at various points in time (i.e. pre invocation and post invocation) at both the function level and app level (meaning you register it once and it runs for all functions).
The main scenario is to simplify users integrating with the Application Insights sdk for Node.js. Users can already do it, but it's a bit complicated (see docs here). If we were to add pre and post invocation hooks, most of that logic could be shifted to the sdk itself instead of the user's code. Some work was done in this PR, but the hooks were never actually exposed or usable.
Also, users could leverage these hooks for any reason (other than app insights) so IMO we need to make sure this is an "official" api. The Python team did this by adding worker extensions which we may or may not want to model after. NOTE: It would be much easier for us to support app-level hooks after the new programming model changes.