|
| 1 | +# Azure Functions |
| 2 | + |
| 3 | +The Azure Function handler can handle the Azure Functions V4 programming model. |
| 4 | + |
| 5 | +```typescript |
| 6 | +import { app } from '@azure/functions'; |
| 7 | +import { createAzureFunctionHandler } from '@ts-rest/serverless/azure'; |
| 8 | +import { contract } from './contract'; |
| 9 | +import { router } from './router'; |
| 10 | + |
| 11 | +const handler = createAzureFunctionHandler(contract, router, { |
| 12 | + // options |
| 13 | +}); |
| 14 | + |
| 15 | +// This will register a single function handler for the handler |
| 16 | +app.http('api', { |
| 17 | + // Be sure to include any method that the router requires |
| 18 | + methods: ['POST', 'PATCH', 'DELETE', 'GET'], |
| 19 | + authLevel: 'anonymous', |
| 20 | + route: '{*route}', |
| 21 | + handler, |
| 22 | +}); |
| 23 | +``` |
| 24 | + |
| 25 | +## Route Prefix |
| 26 | + |
| 27 | +By default, Azure Functions have a route prefix `api` for every route registered. Unless you specifically have the same in your contract, then you will need to add the following to the end of your `host.json` file to remove this prefix. |
| 28 | + |
| 29 | +```json |
| 30 | +// host.json |
| 31 | +{ |
| 32 | + ..., |
| 33 | + "extensions": { |
| 34 | + "http": { |
| 35 | + "routePrefix": "" |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | +``` |
| 40 | + |
| 41 | +## Context Object |
| 42 | + |
| 43 | +In addition to the regular context properties, the context object for Azure Function handlers includes the following additional properties: |
| 44 | + |
| 45 | +- `rawHttpRequest: HttpRequest`: The raw request that was passed to the Azure Function |
| 46 | +- `azureContext: InvocationContext`: The Azure Function Invocation Context passed with each invocation of a function |
| 47 | + |
| 48 | +```typescript |
| 49 | +import { createLambdaHandler } from '@ts-rest/serverless/aws'; |
| 50 | +import { contract } from './contract'; |
| 51 | + |
| 52 | +export const handler = createAzureFunctionHandler( |
| 53 | + contract, |
| 54 | + { |
| 55 | + getPost: async ({ params: { id } }, { azureContext, rawHttpRequest }) => { |
| 56 | + azureContext.log('Received request!'); |
| 57 | + |
| 58 | + return { |
| 59 | + status: 200, |
| 60 | + body: { |
| 61 | + id, |
| 62 | + title: 'Hello, World!', |
| 63 | + }, |
| 64 | + }; |
| 65 | + }, |
| 66 | + }, |
| 67 | + { |
| 68 | + requestMiddleware: [ |
| 69 | + (request, { rawHttpRequest, azureContext }) => { |
| 70 | + console.log('Raw HttpRequest:', rawHttpRequest); |
| 71 | + console.log('Azure Invocation Context:', azureContext); |
| 72 | + }, |
| 73 | + ], |
| 74 | + responseHandlers: [(response, request, { rawHttpRequest, azureContext }) => {}], |
| 75 | + }, |
| 76 | +); |
| 77 | +``` |
0 commit comments