refactor: make GraphQL Server middleware as handler (#277)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent aa6807c · Browse files · 2 files·+20 added−23 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+20 added−23 removed
- tests:+7 added−0 removed
- other:+13 added−23 removed
Provenance
- Commit
a1d2132- Tree
eb811eb- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
aa6807c
2 files changed+20 added−23 removed
modified:src/middleware/graphql-server/index.test.ts+7 added
37 unmodified lines38 hello: () => 'Hello world!',39 }40 41 const app = new Hono()42+43 app.use(44 '/graphql',45 graphqlServer({46 schema,47 rootValue,48 })49 )50 51+ app.all('*', (c) => {52+ c.header('foo', 'bar')53+ return c.text('fallback')54+ })55+56 it('Should return GraphQL response', async () => {57 const query = 'query { hello }'58 const body = {59 query: query,8 unmodified lines68 })69 expect(res).not.toBeNull()70 expect(res.status).toBe(200)71 expect(await res.text()).toBe('{"data":{"hello":"Hello world!"}}')72+ expect(res.headers.get('foo')).toBeNull() // GraphQL Server middleware should be Handler73 })74 })75 76 const QueryRootType = new GraphQLObjectType({497 unmodified linesmodified:src/middleware/graphql-server/index.ts+13 added-23 removed
38 unmodified lines39 const validationRules = options.validationRules ?? []40 // const showGraphiQL = options.graphiql ?? false41 42 return async (c: Context, next: Next) => {43- await next()44-43 // GraphQL HTTP only supports GET and POST methods.44 if (c.req.method !== 'GET' && c.req.method !== 'POST') {47- c.res = c.json(errorMessages(['GraphQL only supports GET and POST requests.']), 405, {45+ return c.json(errorMessages(['GraphQL only supports GET and POST requests.']), 405, {46 Allow: 'GET, POST',47 })50- return48 }49 50 let params: GraphQLParams51 try {52 params = await getGraphQLParams(c.req)53 } catch (e) {54 if (e instanceof Error) {55 console.error(`${e.stack || e.message}`)59- c.res = c.json(errorMessages([e.message], [e]), 400)56+ return c.json(errorMessages([e.message], [e]), 400)57 }61- return58 }59 60 const { query, variables, operationName } = params61 62 if (query == null) {67- c.res = c.json(errorMessages(['Must provide query string.']), 400)68- return63+ return c.json(errorMessages(['Must provide query string.']), 400)64 }65 66 const schemaValidationErrors = validateSchema(schema)67 if (schemaValidationErrors.length > 0) {68 // Return 500: Internal Server Error if invalid schema.74- c.res = c.json(69+ return c.json(70 errorMessages(['GraphQL schema validation error.'], schemaValidationErrors),71 50072 )78- return73 }74 75 let documentAST: DocumentNode76 try {4 unmodified lines81 console.error(`${syntaxError.stack || syntaxError.message}`)82 const e = new GraphQLError(syntaxError.message, {83 originalError: syntaxError,84 })91- c.res = c.json(errorMessages(['GraphQL syntax error.'], [e]), 400)85+ return c.json(errorMessages(['GraphQL syntax error.'], [e]), 400)86 }93- return87 }88 89 // Validate AST, reporting any errors.90 const validationErrors = validate(schema, documentAST, [...specifiedRules, ...validationRules])91 92 if (validationErrors.length > 0) {93 // Return 400: Bad Request if any validation errors exist.101- c.res = c.json(errorMessages(['GraphQL validation error.'], validationErrors), 400)102- return94+ return c.json(errorMessages(['GraphQL validation error.'], validationErrors), 400)95 }96 97 if (c.req.method === 'GET') {98 // Determine if this GET request will perform a non-query.6 unmodified lines105 }106 */107 108 // Otherwise, report a 405: Method Not Allowed error.117- c.res = c.json(109+ return c.json(110 errorMessages([111 `Can only perform a ${operationAST.operation} operation from a POST request.`,112 ]),113 405,114 { Allow: 'POST' }115 )124- return116 }117 }118 119 let result: FormattedExecutionResult13 unmodified lines133 originalError: contextError,134 nodes: documentAST,135 })136 // Return 400: Bad Request if any execution context errors exist.146- c.res = c.json(errorMessages(['GraphQL execution context error.'], [e]), 400)137+ return c.json(errorMessages(['GraphQL execution context error.'], [e]), 400)138 }148- return139 }140 141 if (result.data == null) {152- c.res = c.json(errorMessages([result.errors.toString()], result.errors), 500)153- return142+ return c.json(errorMessages([result.errors.toString()], result.errors), 500)143 }144 145 /*146 Now, does not support GraphiQL2 unmodified lines149 */150 151 if (pretty) {152 const payload = JSON.stringify(result, null, pretty ? 2 : 0)164- c.res = c.text(payload, 200, {153+ return c.text(payload, 200, {154 'Content-Type': 'application/json',155 })156 } else {168- c.res = c.json(result)157+ return c.json(result)158 }170- return159+160+ await next() // XXX161 }162 }163 164 export interface GraphQLParams {69 unmodified lines