Skip to content
Myr

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

2 files+20 added−23 removed

modified:src/middleware/graphql-server/index.test.ts+7 added
37 unmodified lines
38 hello: () => 'Hello world!',39 }4041 const app = new Hono()4243 app.use(44 '/graphql',45 graphqlServer({46 schema,47 rootValue,48 })49 )5051 app.all('*', (c) => {52 c.header('foo', 'bar')53 return c.text('fallback')54 })5556 it('Should return GraphQL response', async () => {57 const query = 'query { hello }'58 const body = {59 query: query,
8 unmodified lines
68 })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})7576const QueryRootType = new GraphQLObjectType({
497 unmodified lines
modified:src/middleware/graphql-server/index.ts+13 added-23 removed
38 unmodified lines
39 const validationRules = options.validationRules ?? []40 // const showGraphiQL = options.graphiql ?? false4142 return async (c: Context, next: Next) => {43 await next()4443 // 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 }4950 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 }5960 const { query, variables, operationName } = params6162 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 }6566 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 }7475 let documentAST: DocumentNode76 try {
4 unmodified lines
81 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 }8889 // Validate AST, reporting any errors.90 const validationErrors = validate(schema, documentAST, [...specifiedRules, ...validationRules])9192 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 }9697 if (c.req.method === 'GET') {98 // Determine if this GET request will perform a non-query.
6 unmodified lines
105 }106 */107108 // 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 }118119 let result: FormattedExecutionResult
13 unmodified lines
133 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 }140141 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 }144145 /*146 Now, does not support GraphiQL
2 unmodified lines
149 */150151 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 return159160 await next() // XXX161 }162}163164export interface GraphQLParams {
69 unmodified lines