When building an application in Azure Functions you can specify the HTTP Methods that are accepted in the function.json
Given an API that you can do multiple functions on (GET, PUT POST etc) what is the best way to create that function or functions.
There will be shared logic and libraries that need to be available, so I'm looking for a pattern that can enable all the MEthods in a single class, but not sure how you would define that in a function.json such that each HTTP Method could have its own entry point.
The other option is to create a function that basically chooses the method and class that function but this seems like some middleware overhead that I"m sure can be handled in a better way.
i.e. I don't think I should do this for every object that I create a function for and there must be a better pattern.
async HandleRequest(){
return validateJwt(function(context,req){
if(req.method === 'GET'){
}
else if(req.method === 'POST'){
}
else if(req.method === 'DELETE'){
}
else if(req.method === 'PUT'){
}
else if(req.method === 'PATCH'){
}
});
}
So the best method for this is to use multiple functions.
You can define functions by route and method in the function.json file. see the example.
Notice route:family/{id:int}
this is the only route that this function will handle. you also put in the "methods": ["get"]
To restrict the function to a GET.
Create a function per METHOD to have more maintainability in your code. I then use some middleware functionality (which does auth and error handling) before I have a common FamilyHandler Class that does the CRUD operations, including managing the connection to the database.
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": ["get"],
"route": "family/{id:int}"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
I discovered this in the following documentation https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=javascript