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

Add support for a human-readable string whenever passing a maxAge via schema hint or dynamic hints in code #7911

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/warm-ties-add.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@apollo/server-plugin-response-cache': minor
'@apollo/cache-control-types': minor
'@apollo/server': minor
---

Add support for a human-readable string whenever passing a maxAge via schema hint or dynamic hints in code
4 changes: 2 additions & 2 deletions docs/source/performance/caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ description: Configure caching behavior on a per-field basis
type Post {
id: ID!
title: String
author: Author
author: Author @cacheControl(maxAge: "1d")
votes: Int @cacheControl(maxAge: 30)
comments: [Comment]
readByCurrentUser: Boolean! @cacheControl(maxAge: 10, scope: PRIVATE)
Expand Down Expand Up @@ -55,7 +55,7 @@ The `@cacheControl` directive accepts the following arguments:

| Name | Description |
|------|-------------|
| `maxAge` | The maximum amount of time the field's cached value is valid, in seconds. The default value is `0`, but you can [set a different default](#setting-a-different-default-maxage). |
| `maxAge` | The maximum amount of time the field's cached value is valid in seconds or [human-readable string](https://www.npmjs.com/package/ms). The default value is `0`, but you can [set a different default](#setting-a-different-default-maxage). |
| `scope` | If `PRIVATE`, the field's value is specific to a single user. The default value is `PUBLIC`. See also [Identifying users for `PRIVATE` responses](#identifying-users-for-private-responses). |
| `inheritMaxAge` | If `true`, this field inherits the `maxAge` of its parent field instead of using the [default `maxAge`](#setting-a-different-default-maxage). Do not provide `maxAge` if you provide this argument. |

Expand Down
42 changes: 32 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/cache-control-types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export type CacheScope = 'PUBLIC' | 'PRIVATE';
* specify a maxAge and/or a scope.
*/
export interface CacheHint {
maxAge?: number;
maxAge?: number | string;
scope?: CacheScope;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,9 @@ export default function plugin<TContext extends BaseContext>(
// still calls `cache.set` synchronously (ie, that it writes to
// InMemoryLRUCache synchronously).
cache
.set(key, serializedValue, { ttl: policyIfCacheable.maxAge })
.set(key, serializedValue, {
ttl: policyIfCacheable.maxAge as number, // This will always be a number but user can pass in string to the cache hint which gets parsed into a number
})
.catch(logger.warn);
};

Expand Down
2 changes: 2 additions & 0 deletions packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,12 +138,14 @@
"@graphql-tools/schema": "^9.0.0",
"@types/express": "^4.17.13",
"@types/express-serve-static-core": "^4.17.30",
"@types/ms": "^0.7.34",
"@types/node-fetch": "^2.6.1",
"async-retry": "^1.2.1",
"cors": "^2.8.5",
"express": "^4.17.1",
"loglevel": "^1.6.8",
"lru-cache": "^7.10.1",
"ms": "^2.1.3",
"negotiator": "^0.6.3",
"node-abort-controller": "^3.1.1",
"node-fetch": "^2.6.7",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,60 @@ describe('@cacheControl directives', () => {
expect(hints).toStrictEqual(new Map([['droid', { maxAge: 60 }]]));
});

it('should set the specified maxAge from a human-readable cache hint on the field when a string is passed', async () => {
const schema = buildSchemaWithCacheControlSupport(`
type Query {
droid(id: ID!): Droid @cacheControl(maxAge: "1d")
}

type Droid {
id: ID!
name: String!
}
`);

const hints = await collectCacheControlHints(
schema,
`
query {
droid(id: 2001) {
name
}
}
`,
{ defaultMaxAge: 10 },
);

expect(hints).toStrictEqual(new Map([['droid', { maxAge: 86400 }]]));
});

it('should set the default maxAge cache hint on the field when an invalid string is passed', async () => {
const schema = buildSchemaWithCacheControlSupport(`
type Query {
droid(id: ID!): Droid @cacheControl(maxAge: "1ddddd")
}

type Droid {
id: ID!
name: String!
}
`);

const hints = await collectCacheControlHints(
schema,
`
query {
droid(id: 2001) {
name
}
}
`,
{ defaultMaxAge: 10 },
);

expect(hints).toStrictEqual(new Map([['droid', { maxAge: 10 }]]));
});

it('should set the specified maxAge for a field from a cache hint on the target type', async () => {
const schema = buildSchemaWithCacheControlSupport(`
type Query {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,42 @@ describe('plugin', () => {
);
});

// start
it('should set cache-control headers to default max age when provided a defaultMaxAge', async () => {
const response = await makePluginWithOptions({
pluginInitializationOptions: {
calculateHttpHeaders: true,
defaultMaxAge: 100,
},
});
expect(response.headers.get('cache-control')).toBe(
'max-age=100, public',
);
});

it('should set cache-control headers to default max age when provided a defaultMaxAge in a human readable format', async () => {
const response = await makePluginWithOptions({
pluginInitializationOptions: {
calculateHttpHeaders: true,
defaultMaxAge: '1d',
},
});
expect(response.headers.get('cache-control')).toBe(
'max-age=86400, public',
);
});

it('should not set cache-control headers when provided a defaultMaxAge in a invalid human readable format', async () => {
const response = await makePluginWithOptions({
pluginInitializationOptions: {
calculateHttpHeaders: true,
defaultMaxAge: '1ddddd',
},
});
expect(response.headers.get('cache-control')).toBe('no-store');
});
// end

const shouldNotSetCacheControlHeader = (
response: HTTPGraphQLResponse,
) => {
Expand Down
Loading