Skip to content
Myr

feat: add GraphQL server middleware (#142)

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 6294c84 · Browse files · 6 files+871 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+871 added−0 removed

  • tests:+625 added−0 removed
  • other:+246 added−0 removed

6 files+871 added−0 removed

added:src/middleware/graphql-server/graphql-server.test.ts+564 added
1import { Hono } from '../../hono'2import { errorMessages, graphqlServer } from './graphql-server'3import {4 buildSchema,5 GraphQLSchema,6 GraphQLString,7 GraphQLObjectType,8 GraphQLNonNull,9} from 'graphql'1011describe('errorMessages', () => {12 const messages = errorMessages(['message a', 'message b'])13 expect(messages).toEqual({14 errors: [15 {16 message: 'message a',17 },18 {19 message: 'message b',20 },21 ],22 })23})2425describe('GraphQL Middleware - Simple way', () => {26 // Construct a schema, using GraphQL schema language27 const schema = buildSchema(`28 type Query {29 hello: String30 }31`)3233 // The root provides a resolver function for each API endpoint34 const rootValue = {35 hello: () => 'Hello world!',36 }3738 const app = new Hono()39 app.use(40 '/graphql',41 graphqlServer({42 schema,43 rootValue,44 })45 )4647 it('Should return GraphQL response', async () => {48 const query = 'query { hello }'49 const body = {50 query: query,51 }5253 const res = await app.request('http://localhost/graphql', {54 method: 'POST',55 headers: {56 'Content-Type': 'application/json',57 },58 body: JSON.stringify(body),59 })60 expect(res).not.toBeNull()61 expect(res.status).toBe(200)62 expect(await res.text()).toBe('{"data":{"hello":"Hello world!"}}')63 })64})6566const QueryRootType = new GraphQLObjectType({67 name: 'QueryRoot',68 fields: {69 test: {70 type: GraphQLString,71 args: {72 who: { type: GraphQLString },73 },74 resolve: (_root, args: { who?: string }) => 'Hello ' + (args.who ?? 'World'),75 },76 thrower: {77 type: GraphQLString,78 resolve() {79 throw new Error('Throws!')80 },81 },82 },83})8485const TestSchema = new GraphQLSchema({86 query: QueryRootType,87 mutation: new GraphQLObjectType({88 name: 'MutationRoot',89 fields: {90 writeTest: {91 type: QueryRootType,92 resolve: () => ({}),93 },94 },95 }),96})9798const urlString = (query?: Record<string, string>): string => {99 const base = 'http://localhost/graphql'100 if (!query) return base101 const queryString = new URLSearchParams(query).toString()102 return `${base}?${queryString}`103}104105describe('GraphQL Middleware - GET functionality', () => {106 const app = new Hono()107 app.use(108 '/graphql',109 graphqlServer({110 schema: TestSchema,111 })112 )113114 it('Allows GET with variable values', async () => {115 const query = {116 query: 'query helloWho($who: String){ test(who: $who) }',117 variables: JSON.stringify({ who: 'Dolly' }),118 }119120 const res = await app.request(urlString(query), {121 method: 'GET',122 })123 expect(res.status).toBe(200)124 expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')125 })126127 it('Allows GET with operation name', async () => {128 const query = {129 query: `130 query helloYou { test(who: "You"), ...shared }131 query helloWorld { test(who: "World"), ...shared }132 query helloDolly { test(who: "Dolly"), ...shared }133 fragment shared on QueryRoot {134 shared: test(who: "Everyone")135 }136 `,137 operationName: 'helloWorld',138 }139140 const res = await app.request(urlString(query), {141 method: 'GET',142 })143 expect(res.status).toBe(200)144 expect(await res.json()).toEqual({145 data: {146 test: 'Hello World',147 shared: 'Hello Everyone',148 },149 })150 })151152 it('Reports validation errors', async () => {153 const query = { query: '{ test, unknownOne, unknownTwo }' }154 const res = await app.request(urlString(query), {155 method: 'GET',156 })157 expect(res.status).toBe(400)158 })159160 it('Errors when missing operation name', async () => {161 const query = {162 query: `163 query TestQuery { test }164 mutation TestMutation { writeTest { test } }165 `,166 }167 const res = await app.request(urlString(query), {168 method: 'GET',169 })170 expect(res.status).toBe(500)171 })172173 it('Errors when sending a mutation via GET', async () => {174 const query = {175 query: 'mutation TestMutation { writeTest { test } }',176 }177 const res = await app.request(urlString(query), {178 method: 'GET',179 })180 expect(res.status).toBe(405)181 })182183 it('Errors when selecting a mutation within a GET', async () => {184 const query = {185 operationName: 'TestMutation',186 query: `187 query TestQuery { test }188 mutation TestMutation { writeTest { test } }189 `,190 }191 const res = await app.request(urlString(query), {192 method: 'GET',193 })194 expect(res.status).toBe(405)195 })196197 it('Allows a mutation to exist within a GET', async () => {198 const query = {199 operationName: 'TestQuery',200 query: `201 mutation TestMutation { writeTest { test } }202 query TestQuery { test }203 `,204 }205 const res = await app.request(urlString(query), {206 method: 'GET',207 })208 expect(res.status).toBe(200)209 expect(await res.json()).toEqual({210 data: {211 test: 'Hello World',212 },213 })214 })215})216217describe('GraphQL Middleware - POST functionality', () => {218 const app = new Hono()219 app.use(220 '/graphql',221 graphqlServer({222 schema: TestSchema,223 })224 )225226 it('Allows POST with JSON encoding', async () => {227 const query = { query: '{test}' }228229 const res = await app.request(urlString(), {230 method: 'POST',231 headers: {232 'Content-Type': 'application/json',233 },234 body: JSON.stringify(query),235 })236 expect(res.status).toBe(200)237 expect(await res.text()).toBe('{"data":{"test":"Hello World"}}')238 })239240 it('Allows sending a mutation via POST', async () => {241 const query = { query: 'mutation TestMutation { writeTest { test } }' }242 const res = await app.request(urlString(), {243 method: 'POST',244 headers: {245 'Content-Type': 'application/json',246 },247 body: JSON.stringify(query),248 })249 expect(res.status).toBe(200)250 expect(await res.text()).toBe('{"data":{"writeTest":{"test":"Hello World"}}}')251 })252253 it('Allows POST with url encoding', async () => {254 const query = {255 query: '{test}',256 }257 const res = await app.request(urlString(query), {258 method: 'POST',259 })260 expect(res.status).toBe(200)261 expect(await res.text()).toBe('{"data":{"test":"Hello World"}}')262 })263264 it('Supports POST JSON query with string variables', async () => {265 const query = {266 query: 'query helloWho($who: String){ test(who: $who) }',267 variables: JSON.stringify({ who: 'Dolly' }),268 }269 const res = await app.request(urlString(), {270 method: 'POST',271 headers: {272 'Content-Type': 'application/json',273 },274 body: JSON.stringify(query),275 })276 expect(res.status).toBe(200)277 expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')278 })279280 it('Supports POST url encoded query with string variables', async () => {281 const searchParams = new URLSearchParams({282 query: 'query helloWho($who: String){ test(who: $who) }',283 variables: JSON.stringify({ who: 'Dolly' }),284 })285 const res = await app.request(urlString(), {286 method: 'POST',287 headers: {288 'Content-Type': 'application/x-www-form-urlencoded',289 },290 body: searchParams.toString(),291 })292 expect(res.status).toBe(200)293 expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')294 })295296 it('Supports POST JSON query with GET variable values', async () => {297 const variables = {298 variables: JSON.stringify({ who: 'Dolly' }),299 }300 const query = { query: 'query helloWho($who: String){ test(who: $who) }' }301 const res = await app.request(urlString(variables), {302 method: 'POST',303 headers: {304 'Content-Type': 'application/json',305 },306 body: JSON.stringify(query),307 })308 expect(res.status).toBe(200)309 expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')310 })311312 it('Supports POST url encoded query with GET variable values', async () => {313 const searchParams = new URLSearchParams({314 query: 'query helloWho($who: String){ test(who: $who) }',315 })316 const variables = {317 variables: JSON.stringify({ who: 'Dolly' }),318 }319 const res = await app.request(urlString(variables), {320 method: 'POST',321 headers: {322 'Content-Type': 'application/x-www-form-urlencoded',323 },324 body: searchParams.toString(),325 })326 expect(res.status).toBe(200)327 expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')328 })329330 it('Supports POST raw text query with GET variable values', async () => {331 const variables = {332 variables: JSON.stringify({ who: 'Dolly' }),333 }334 const res = await app.request(urlString(variables), {335 method: 'POST',336 headers: {337 'Content-Type': 'application/graphql',338 },339 body: 'query helloWho($who: String){ test(who: $who) }',340 })341 expect(res.status).toBe(200)342 expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')343 })344345 it('Allows POST with operation name', async () => {346 const query = {347 query: `348 query helloYou { test(who: "You"), ...shared }349 query helloWorld { test(who: "World"), ...shared }350 query helloDolly { test(who: "Dolly"), ...shared }351 fragment shared on QueryRoot {352 shared: test(who: "Everyone")353 }354 `,355 operationName: 'helloWorld',356 }357 const res = await app.request(urlString(), {358 method: 'POST',359 headers: {360 'Content-Type': 'application/json',361 },362 body: JSON.stringify(query),363 })364 expect(res.status).toBe(200)365 expect(await res.json()).toEqual({366 data: {367 test: 'Hello World',368 shared: 'Hello Everyone',369 },370 })371 })372373 it('Allows POST with GET operation name', async () => {374 const res = await app.request(375 urlString({376 operationName: 'helloWorld',377 }),378 {379 method: 'POST',380 headers: {381 'Content-Type': 'application/graphql',382 },383 body: `384 query helloYou { test(who: "You"), ...shared }385 query helloWorld { test(who: "World"), ...shared }386 query helloDolly { test(who: "Dolly"), ...shared }387 fragment shared on QueryRoot {388 shared: test(who: "Everyone")389 }390 `,391 }392 )393 expect(res.status).toBe(200)394 expect(await res.json()).toEqual({395 data: {396 test: 'Hello World',397 shared: 'Hello Everyone',398 },399 })400 })401})402403describe('Pretty printing', () => {404 it('Supports pretty printing', async () => {405 const app = new Hono()406407 app.use(408 '/graphql',409 graphqlServer({410 schema: TestSchema,411 pretty: true,412 })413 )414415 const res = await app.request(urlString({ query: '{test}' }))416 expect(await res.text()).toEqual(417 [418 // Pretty printed JSON419 '{',420 ' "data": {',421 ' "test": "Hello World"',422 ' }',423 '}',424 ].join('\n')425 )426 })427})428429describe('Error handling functionality', () => {430 const app = new Hono()431 app.use(432 '/graphql',433 graphqlServer({434 schema: TestSchema,435 })436 )437438 it('Handles query errors from non-null top field errors', async () => {439 const schema = new GraphQLSchema({440 query: new GraphQLObjectType({441 name: 'Query',442 fields: {443 test: {444 type: new GraphQLNonNull(GraphQLString),445 resolve() {446 throw new Error('Throws!')447 },448 },449 },450 }),451 })452 const app = new Hono()453454 app.use('/graphql', graphqlServer({ schema }))455456 const res = await app.request(457 urlString({458 query: '{ test }',459 })460 )461462 expect(res.status).toBe(500)463 })464465 it('Handles syntax errors caught by GraphQL', async () => {466 const res = await app.request(467 urlString({468 query: 'syntax_error',469 }),470 {471 method: 'GET',472 }473 )474475 expect(res.status).toBe(400)476 })477478 it('Handles errors caused by a lack of query', async () => {479 const res = await app.request(urlString(), {480 method: 'GET',481 })482483 expect(res.status).toBe(400)484 })485486 it('Handles invalid JSON bodies', async () => {487 const res = await app.request(urlString(), {488 method: 'POST',489 headers: {490 'Content-Type': 'application/json',491 },492 body: JSON.stringify([]),493 })494495 expect(res.status).toBe(400)496 })497498 it('Handles incomplete JSON bodies', async () => {499 const res = await app.request(urlString(), {500 method: 'POST',501 headers: {502 'Content-Type': 'application/json',503 },504 body: '{"query":',505 })506 expect(res.status).toBe(400)507 })508509 it('Handles plain POST text', async () => {510 const res = await app.request(511 urlString({512 variables: JSON.stringify({ who: 'Dolly' }),513 }),514 {515 method: 'POST',516 headers: {517 'Content-Type': 'text/plain',518 },519 body: 'query helloWho($who: String){ test(who: $who) }',520 }521 )522 expect(res.status).toBe(400)523 })524525 it('Handles poorly formed variables', async () => {526 const res = await app.request(527 urlString({528 variables: 'who:You',529 query: 'query helloWho($who: String){ test(who: $who) }',530 }),531 {532 method: 'GET',533 }534 )535 expect(res.status).toBe(400)536 })537538 it('Handles invalid variables', async () => {539 const res = await app.request(urlString(), {540 method: 'POST',541 headers: {542 'Content-Type': 'application/json',543 },544 body: JSON.stringify({545 query: 'query helloWho($who: String){ test(who: $who) }',546 variables: { who: ['John', 'Jane'] },547 }),548 })549550 expect(res.status).toBe(500)551 })552553 it('Handles unsupported HTTP methods', async () => {554 const res = await app.request(urlString({ query: '{test}' }), {555 method: 'PUT',556 })557558 expect(res.status).toBe(405)559 expect(res.headers.get('allow')).toBe('GET, POST')560 expect(await res.json()).toEqual({561 errors: [{ message: 'GraphQL only supports GET and POST requests.' }],562 })563 })564})
added:src/middleware/graphql-server/graphql-server.ts+210 added
1// Based on the code in the `express-graphql` package.2// https://github.com/graphql/express-graphql/blob/main/src/index.ts34import { parseBody } from './parse-body'5import type { Context } from '../../context'67import {8 Source,9 parse,10 execute,11 validateSchema,12 validate,13 specifiedRules,14 getOperationAST,15} from 'graphql'1617import type { GraphQLSchema, DocumentNode, ValidationRule, FormattedExecutionResult } from 'graphql'1819type Options = {20 schema: GraphQLSchema21 rootValue?: unknown22 pretty?: boolean23 validationRules?: ReadonlyArray<ValidationRule>24 // graphiql?: boolean25}2627export const graphqlServer = (options: Options) => {28 const schema = options.schema29 const rootValue = options.rootValue30 const pretty = options.pretty ?? false31 const validationRules = options.validationRules ?? []32 // const showGraphiQL = options.graphiql ?? false3334 return async (c: Context, next: Function) => {35 await next()3637 // GraphQL HTTP only supports GET and POST methods.38 if (c.req.method !== 'GET' && c.req.method !== 'POST') {39 c.res = c.json(errorMessages(['GraphQL only supports GET and POST requests.']), 405, {40 Allow: 'GET, POST',41 })42 return43 }4445 let params: GraphQLParams46 try {47 params = await getGraphQLParams(c.req)48 } catch (e) {49 if (e instanceof Error) {50 c.res = c.json(errorMessages([e.message]), 400)51 }52 return53 }5455 const { query, variables, operationName } = params5657 if (query == null) {58 c.res = c.json(errorMessages(['Must provide query string.']), 400)59 return60 }6162 const schemaValidationErrors = validateSchema(schema)63 if (schemaValidationErrors.length > 0) {64 // Return 500: Internal Server Error if invalid schema.65 c.res = c.json(errorMessages(['GraphQL schema validation error.']), 500)66 return67 }6869 let documentAST: DocumentNode70 try {71 documentAST = parse(new Source(query, 'GraphQL request'))72 } catch (syntaxError: unknown) {73 // Return 400: Bad Request if any syntax errors errors exist.74 c.res = c.json(errorMessages(['GraphQL syntax error.']), 400)75 return76 }7778 // Validate AST, reporting any errors.79 const validationErrors = validate(schema, documentAST, [...specifiedRules, ...validationRules])8081 if (validationErrors.length > 0) {82 // Return 400: Bad Request if any validation errors exist.83 c.res = c.json(errorMessages(['GraphQL validation error.']), 400)84 return85 }8687 if (c.req.method === 'GET') {88 // Determine if this GET request will perform a non-query.89 const operationAST = getOperationAST(documentAST, operationName)90 if (operationAST && operationAST.operation !== 'query') {91 /*92 Now , does not support GraphiQL93 if (showGraphiQL) {94 //return respondWithGraphiQL(response, graphiqlOptions, params)95 }96 */9798 // Otherwise, report a 405: Method Not Allowed error.99 c.res = c.json(100 errorMessages([101 `Can only perform a ${operationAST.operation} operation from a POST request.`,102 ]),103 405,104 { Allow: 'POST' }105 )106 return107 }108 }109110 let result: FormattedExecutionResult111112 try {113 result = await execute({114 schema,115 document: documentAST,116 rootValue,117 variableValues: variables,118 operationName: operationName,119 })120 } catch (error: unknown) {121 // Return 400: Bad Request if any execution context errors exist.122 c.res = c.json(errorMessages(['GraphQL execution context error.']), 400)123 return124 }125126 if (result.data == null) {127 c.res = c.json(errorMessages([result.errors.toString()]), 500)128 return129 }130131 /*132 Now, does not support GraphiQL133 if (showGraphiQL) {134 }135 */136137 if (pretty) {138 const payload = JSON.stringify(result, null, pretty ? 2 : 0)139 c.res = c.text(payload, 200, {140 'Content-Type': 'application/json',141 })142 } else {143 c.res = c.json(result)144 }145 return146 }147}148149export interface GraphQLParams {150 query: string | null151 variables: { readonly [name: string]: unknown } | null152 operationName: string | null153 raw: boolean154}155156export const getGraphQLParams = async (request: Request): Promise<GraphQLParams> => {157 const urlData = new URLSearchParams(request.url.split('?')[1])158 const bodyData = await parseBody(request)159160 // GraphQL Query string.161 let query = urlData.get('query') ?? (bodyData.query as string | null)162163 if (typeof query !== 'string') {164 query = null165 }166167 // Parse the variables if needed.168 let variables = (urlData.get('variables') ?? bodyData.variables) as {169 readonly [name: string]: unknown170 } | null171 if (typeof variables === 'string') {172 try {173 variables = JSON.parse(variables)174 } catch {175 throw Error('Variables are invalid JSON.')176 }177 } else if (typeof variables !== 'object') {178 variables = null179 }180181 // Name of GraphQL operation to execute.182 let operationName = urlData.get('operationName') ?? (bodyData.operationName as string | null)183 if (typeof operationName !== 'string') {184 operationName = null185 }186187 const raw = urlData.get('raw') != null || bodyData.raw !== undefined188189 const params: GraphQLParams = {190 query: query,191 variables: variables,192 operationName: operationName,193 raw: raw,194 }195196 return params197}198199export const errorMessages = (messages: string[]) => {200 const errors = messages.map((message) => {201 return {202 message: message,203 }204 })205 return {206 errors: errors,207 }208}209210export const graphiQLResponse = () => {}
added:src/middleware/graphql-server/parse-body.test.ts+61 added
added:src/middleware/graphql-server/parse-body.ts+26 added
modified:package.json+5 added
modified:yarn.lock+5 added
1978 unmodified lines
1979 version "4.2.9"1980 resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.9.tgz#041b05df45755e587a24942279b9d113146e1c96"1981 integrity sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==19821983graphql@^16.3.0:1984 version "16.3.0"1985 resolved "https://registry.yarnpkg.com/graphql/-/graphql-16.3.0.tgz#a91e24d10babf9e60c706919bb182b53ccdffc05"1986 integrity sha512-xm+ANmA16BzCT5pLjuXySbQVFwH3oJctUVdy81w1sV0vBU0KgDdBGtxQOUd5zqOBk/JayAFeG8Dlmeq74rjm/A==19871988has-bigints@^1.0.1:1989 version "1.0.1"1990 resolved "https://registry.yarnpkg.com/has-bigints/-/has-bigints-1.0.1.tgz#64fe6acb020673e3b78db035a5af69aa9d07b113"1991 integrity sha512-LSBS2LjbNBTf6287JEbEzvJgftkF5qFkmCo9hDRpAzKhUOlJ+hx8dd4USs00SgsUNwc4617J9ki5YtEClM2ffA==
1905 unmodified lines