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(response-cache): use ETag to use HTTP caching strategy #2252

Merged
merged 17 commits into from
Feb 17, 2023
7 changes: 7 additions & 0 deletions .changeset/tame-frogs-shake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@graphql-yoga/plugin-response-cache': minor
---

Support `ETag` and `If-None-Match` headers for HTTP Caching to improve the performance on the client side, also reduce the load on the server.

[Learn how it works](https://the-guild.dev/graphql/yoga-server/docs/features/response-caching)
188 changes: 188 additions & 0 deletions examples/response-cache/__integration-tests__/response-cache.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import { fetch } from '@whatwg-node/fetch'
import { create } from '../src/main.js'

describe('example-response-cache', () => {
beforeEach(() => {
jest.useRealTimers()
})

test('cache stuff', async () => {
jest.useFakeTimers()

const [port, close] = await create()
try {
let response = await fetch(`http://localhost:${port}/graphql`, {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json',
},
body: JSON.stringify({
query: /* GraphQL */ `
query {
me {
id
}
}
`,
}),
})

expect(response.status).toEqual(200)
expect(response.headers.get('etag')).toMatchInlineSnapshot(
`"7490da5629533a4fc101a2188569a79b776d6a3d75920287e6fa9b203f2e8d34"`,
)
const lastModified = response.headers.get('last-modified')
expect(lastModified).toBeDefined()

jest.advanceTimersByTime(1000)

response = await fetch(`http://localhost:${port}/graphql`, {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json',
},
body: JSON.stringify({
query: /* GraphQL */ `
query {
me {
id
}
}
`,
}),
})

expect(response.status).toEqual(200)
expect(response.headers.get('etag')).toMatchInlineSnapshot(
`"7490da5629533a4fc101a2188569a79b776d6a3d75920287e6fa9b203f2e8d34"`,
)
const newLastModified = response.headers.get('last-modified')
expect(lastModified).toEqual(newLastModified)
} finally {
await close()
}
})

test('cache with TTL', async () => {
jest.useFakeTimers()

const [port, close] = await create({
ttlPerType: {
User: 500,
},
})
try {
let response = await fetch(`http://localhost:${port}/graphql`, {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json',
},
body: JSON.stringify({
query: /* GraphQL */ `
query {
me {
id
}
}
`,
}),
})

expect(response.status).toEqual(200)
expect(response.headers.get('etag')).toMatchInlineSnapshot(
`"7490da5629533a4fc101a2188569a79b776d6a3d75920287e6fa9b203f2e8d34"`,
)
const lastModified = new Date(
response.headers.get('last-modified')!,
).getTime()

jest.advanceTimersByTime(1000)

response = await fetch(`http://localhost:${port}/graphql`, {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json',
},
body: JSON.stringify({
query: /* GraphQL */ `
query {
me {
id
}
}
`,
}),
})

expect(response.status).toEqual(200)
expect(response.headers.get('etag')).toMatchInlineSnapshot(
`"7490da5629533a4fc101a2188569a79b776d6a3d75920287e6fa9b203f2e8d34"`,
)

const diff =
new Date(response.headers.get('last-modified')!).getTime() -
lastModified

// diff should be 1000 because we forwarded by 1000ms and the cache only caches for 500ms
expect(diff).toEqual(1000)
} finally {
await close()
}
})

test('cache with ETag and If-None-Match', async () => {
const [port, close] = await create({
ttlPerType: {
User: 500,
},
})
try {
let response = await fetch(`http://localhost:${port}/graphql`, {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json',
},
body: JSON.stringify({
query: /* GraphQL */ `
query {
me {
id
}
}
`,
}),
})

expect(response.status).toEqual(200)
const etag = response.headers.get('etag')

response = await fetch(`http://localhost:${port}/graphql`, {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json',
'if-none-match': etag!,
},
body: JSON.stringify({
query: /* GraphQL */ `
query {
me {
id
}
}
`,
}),
})

expect(response.status).toEqual(304)
expect(await response.text()).toEqual('')
} finally {
await close()
}
})
})
27 changes: 27 additions & 0 deletions examples/response-cache/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "example-response-cache",
"version": "0.1.11",
"private": true,
"description": "",
"scripts": {
"dev": "cross-env NODE_ENV=development ts-node-dev --exit-child --respawn src/main.ts",
"start": "ts-node src/main.ts",
"check": "tsc --pretty --noEmit"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "18.11.11",
"cross-env": "7.0.3",
"ts-node": "10.9.1",
"ts-node-dev": "2.0.0",
"typescript": "4.9.4"
},
"dependencies": {
"graphql-yoga": "3.1.2",
"@graphql-yoga/plugin-response-cache": "1.6.1",
"graphql": "16.6.0"
},
"module": "commonjs"
}
65 changes: 65 additions & 0 deletions examples/response-cache/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { createServer } from 'http'
import { createYoga, createSchema } from 'graphql-yoga'
import {
useResponseCache,
UseResponseCacheParameter,
} from '@graphql-yoga/plugin-response-cache'

const schema = createSchema({
typeDefs: /* GraphQL */ `
type Query {
me: User
}
type User {
id: ID!
name: String!
}
`,
resolvers: {
Query: {
me: () => {
return {
id: '1',
name: 'Bob',
}
},
},
},
})

export const create = (
config?: Omit<UseResponseCacheParameter, 'session'>,
port?: number,
) => {
const yoga = createYoga({
schema,
plugins: [
useResponseCache({
session: () => null,
...config,
}),
],
logging: port !== undefined,
})

const server = createServer(yoga)

return new Promise<[number, () => Promise<void>]>((resolve) => {
server.listen(port, () => {
resolve([
(server.address() as any).port as number,
() =>
new Promise<void>((resolve) => {
server.close(() => {
resolve()
})
}),
])
})
})
}

if (require.main === module) {
create(undefined, 4000)
console.log(`Server is running on http://localhost:4000`)
}
13 changes: 13 additions & 0 deletions examples/response-cache/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"outDir": "./dist",
"module": "commonjs",
"target": "esnext",
"lib": ["esnext"],
"moduleResolution": "node",
"sourceMap": true,
"skipLibCheck": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
1 change: 1 addition & 0 deletions packages/graphql-yoga/src/plugins/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ export type ResultProcessor = (
export interface OnResultProcessEventPayload {
request: Request
result: ResultProcessorInput
setResult(result: ResultProcessorInput): void
resultProcessor?: ResultProcessor
acceptableMediaTypes: string[]
setResultProcessor(
Expand Down
3 changes: 3 additions & 0 deletions packages/graphql-yoga/src/process-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ export async function processResult({
request,
acceptableMediaTypes,
result,
setResult(newResult) {
result = newResult
},
resultProcessor,
setResultProcessor(newResultProcessor, newAcceptedMimeType) {
resultProcessor = newResultProcessor
Expand Down
Loading