Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: uniquely identify batched queries #849

Merged
merged 6 commits into from
Aug 29, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ export interface PubSub {
export interface MercuriusContext {
app: FastifyInstance;
reply: FastifyReply;
operationsCount?: number;
operationId?: number;
__currentQuery: string;
/**
* __Caution__: Only available if `subscriptions` are enabled
*/
Expand Down
24 changes: 17 additions & 7 deletions lib/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -352,13 +352,23 @@ module.exports = async function (app, opts) {

if (allowBatchedQueries && Array.isArray(request.body)) {
// Batched query
return Promise.all(request.body.map(r =>
execute(r, request, reply)
.catch(e => {
const { response } = errorFormatter(e, request[kRequestContext])
return response
})
))
const operationsCount = request.body.length

Object.assign(request[kRequestContext], { operationsCount })

return Promise.all(request.body.map(async (r, operationId) => {
// Create individual reqs for multiple operations, otherwise reference the original req
const operationReq = operationsCount > 1 ? Object.create(request) : request
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would like to hear @mcollina's opinion on the approach to cloning a request object. We need it to be cloned because every query in the batch needs a different context, but I don't know if this is a sensible way to clone it


Object.assign(operationReq[kRequestContext], { operationId })

try {
return await execute(r, operationReq, reply)
} catch (e) {
const { response } = errorFormatter(e, request[kRequestContext])
return response
}
}))
} else {
// Regular query
return execute(request.body, request, reply)
Expand Down
42 changes: 42 additions & 0 deletions test/batched.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const { test } = require('tap')
const Fastify = require('fastify')
const sinon = require('sinon')
const GQL = require('..')

test('POST regular query', async (t) => {
Expand Down Expand Up @@ -346,3 +347,44 @@ test('POST batched query with a resolver which succeeds and a resolver which thr

t.same(JSON.parse(res.body), [{ data: { add: 3 } }, { data: null, errors: [{ message: 'Internal Server Error' }] }])
})

test('POST batched query has an individual context for each operation', async (t) => {
const app = Fastify()

const contextSpy = sinon.spy()

const schema = `
type Query {
test: String
}
`

const resolvers = {
test: (_, ctx) => contextSpy(ctx.operationId, ctx.operationsCount, ctx.__currentQuery)
}

app.register(GQL, {
schema,
resolvers,
allowBatchedQueries: true
})

await app.inject({
method: 'POST',
url: '/graphql',
body: [
{
operationName: 'TestQuery',
query: 'query TestQuery { test }'
},
{
operationName: 'DoubleQuery',
query: 'query DoubleQuery { test }'
}
]
})

t.ok(contextSpy.calledTwice)
t.ok(contextSpy.calledWith(0, 2, sinon.match(/TestQuery/)))
t.ok(contextSpy.calledWith(1, 2, sinon.match(/DoubleQuery/)))
simoneb marked this conversation as resolved.
Show resolved Hide resolved
})
9 changes: 8 additions & 1 deletion test/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { expectAssignable, expectError } from 'tsd'
import { expectAssignable, expectError, expectType } from 'tsd'
/* eslint-disable no-unused-expressions */
import { EventEmitter } from 'events'
// eslint-disable-next-line no-unused-vars
Expand Down Expand Up @@ -780,3 +780,10 @@ expectError(() => {
expectError(() => {
return mercurius.defaultErrorFormatter({}, undefined)
})

// Context contains correct information about (batched) query identity
app.graphql.addHook('onResolution', async function (_execution, context) {
expectType<number | undefined>(context.operationId)
expectType<number | undefined>(context.operationsCount)
expectType<string>(context.__currentQuery)
})