thaitype / nammatham

Azure Functions Framework
https://nammatham.thaitype.dev/
MIT License
67 stars 2 forks source link

Add Middleware #100

Open mildronize opened 10 months ago

mildronize commented 10 months ago

Consider to add middleware at 2 levels: app (NammathamApp) and func level.

However, NammathamApp doesn't handle request or triggers by itself, consider to add middleware for func level will be easier to manipulate.

Expected Behavior

import { initNammatham } from '@nammatham/core';
import { AzureFunctionsAdapter } from '@nammatham/azure-functions';
import { middleware, beforeMiddleware, afterMiddleware } from './middlewares';

const n = initNammatham.create(new AzureFunctionsAdapter());
export const func = n.func;

// Add middleware
func.use(middleware);

// Add middleware before each function to be invoked
func.useBefore(beforeMiddleware);

// Add middleware after each function to be invoked
func.useAfter(afterMiddleware);

// Add middleware to a specific function
export default func
  .httpGet('hello')
  .use(validationMiddleware)
  .handler(async ({ trigger, context } ) => ({ body: 'OK' }) )

Related Repo:

mildronize commented 10 months ago

The official repo has been developing hook feature

https://github.com/Azure/azure-functions-nodejs-library/labels/hooks

https://github.com/Azure/azure-functions-nodejs-worker/issues/664

mildronize commented 10 months ago

Be make sure type safe during middleware

func
.httpGet('hello')
.use(( ctx, next )=> {
  return next({
    ctx,
    data: 'my injected data'
  });
})
.handler(async ({ data } ) => ({ body: data }) );
// The result will be 'my injected data'