Description
Split out from Azure/azure-functions-nodejs-worker#664.
One use-case for hooks is to be able to add additional stuff to a Function, say a CosmosClient
so that the Function can do operations against CosmosDB that aren't possible via a binding.
Initially, it might seem like that's something you could use the hookData
property for, but that's only persisted across the hooks, and not provided to the Function.
It is possible to use the InvocationContext
as a way to pass stuff, but it's typed as unknown
(but this is something we could address with #7) so you have to cast it to something else to work with. Here's how I did it with the new programming model:
registerHook("preInvocation", async (context) => {
const client = new CosmosClient(process.env.CosmosConnectionString);
const { database } = await client.databases.createIfNotExists({
id: "TodoList",
});
const { container } = await database.containers.createIfNotExists({
id: "Items",
partitionKey: { paths: ["/id"] },
});
const ctx = context.invocationContext as any;
ctx.extraInputs.set("cosmosContainer", container);
});
But if instead we had an explicit method, like setFunctionData
on the hook context object, then we could write hooks that are simplified across the different programming models.