|
| 1 | +import { envelop, useLogger, useSchema, useTiming } from '@envelop/core'; |
| 2 | +import { makeExecutableSchema } from '@graphql-tools/schema'; |
| 3 | +import { AzureFunction, Context, HttpRequest } from '@azure/functions'; |
| 4 | +import { getGraphQLParameters, processRequest, Response } from 'graphql-helix'; |
| 5 | + |
| 6 | +const schema = makeExecutableSchema({ |
| 7 | + typeDefs: /* GraphQL */ ` |
| 8 | + type Query { |
| 9 | + hello: String! |
| 10 | + } |
| 11 | + `, |
| 12 | + resolvers: { |
| 13 | + Query: { |
| 14 | + hello: () => 'World', |
| 15 | + }, |
| 16 | + }, |
| 17 | +}); |
| 18 | + |
| 19 | +const getEnveloped = envelop({ |
| 20 | + plugins: [useSchema(schema), useLogger(), useTiming()], |
| 21 | +}); |
| 22 | + |
| 23 | +const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> { |
| 24 | + const { parse, validate, contextFactory, execute, schema } = getEnveloped(); |
| 25 | + const request = { |
| 26 | + body: req.body, |
| 27 | + headers: req.headers, |
| 28 | + method: req.method, |
| 29 | + query: req.query, |
| 30 | + }; |
| 31 | + |
| 32 | + const { operationName, query, variables } = getGraphQLParameters(request); |
| 33 | + const result = (await processRequest({ |
| 34 | + operationName, |
| 35 | + query, |
| 36 | + variables, |
| 37 | + request, |
| 38 | + schema, |
| 39 | + parse, |
| 40 | + validate, |
| 41 | + execute, |
| 42 | + contextFactory, |
| 43 | + })) as Response<any, any>; |
| 44 | + |
| 45 | + context.res = { |
| 46 | + status: 200, |
| 47 | + headers: result.headers.reduce((prev, item) => ({ ...prev, [item.name]: item.value }), {}), |
| 48 | + body: JSON.stringify(result.payload), |
| 49 | + }; |
| 50 | +}; |
| 51 | + |
| 52 | +export default httpTrigger; |
0 commit comments