-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #6 from thuoe/feature/thu-47-new-directive-cache
[THU-47]: @cache directive
- Loading branch information
Showing
5 changed files
with
239 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import { MapperKind, getDirective, mapSchema } from '@graphql-tools/utils' | ||
import { GraphQLError, GraphQLSchema, defaultFieldResolver } from 'graphql' | ||
|
||
interface CachingImpl { | ||
has: (key: string) => Promise<boolean> | ||
get: (key: string) => Promise<string> | ||
set: (key: string, value: string) => Promise<void> | ||
delete: (key: string) => Promise<boolean> | ||
} | ||
|
||
const map = new Map<string, string>() | ||
|
||
const inMemoryCache: CachingImpl = { | ||
has: (key: string) => Promise.resolve(map.has(key)), | ||
get: (key: string) => Promise.resolve(map.get(key)), | ||
delete: (key: string) => Promise.resolve(map.delete(key)), | ||
set: async (key: string, value: string) => { | ||
Promise.resolve(map.set(key, value)) | ||
}, | ||
} | ||
|
||
const cacheDirective = (directiveName: string, cache: CachingImpl = inMemoryCache) => { | ||
return { | ||
cacheDirectiveTypeDefs: `directive @${directiveName}(key: String, ttl: Int) on FIELD_DEFINITION`, | ||
cacheDirectiveTransformer: (schema: GraphQLSchema) => mapSchema(schema, { | ||
[MapperKind.OBJECT_FIELD]: fieldConfig => { | ||
const { resolve = defaultFieldResolver } = fieldConfig | ||
const cacheDirective = getDirective(schema, fieldConfig, directiveName)?.[0] | ||
if (cacheDirective) { | ||
const { ttl, key } = cacheDirective | ||
return { | ||
...fieldConfig, | ||
resolve: async (source, args, context, info) => { | ||
const { returnType } = info | ||
const exists = await cache.has(key) | ||
if (exists) { | ||
const value = await cache.get(key) | ||
if (returnType.toString() === 'String') { | ||
return value | ||
} | ||
if (returnType.toString() === 'Boolean') { | ||
const boolValue = (/true/).test(value); | ||
return boolValue | ||
} | ||
if (returnType.toString() === 'Int') { | ||
return Number(value) | ||
} | ||
try { | ||
return JSON.parse(value) | ||
} catch (error) { | ||
throw new GraphQLError(`Error parsing field value: ${returnType.toString()}`) | ||
} | ||
} | ||
const result = await resolve(source, args, context, info) | ||
cache.set(key, JSON.stringify(result)) | ||
setTimeout(async () => { | ||
await cache.delete(key) | ||
}, ttl) | ||
return result | ||
} | ||
} | ||
} | ||
} | ||
} | ||
) | ||
} | ||
} | ||
|
||
export default cacheDirective |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
import { ApolloServer } from '@apollo/server'; | ||
import cacheDirective from '@src/directives/cache'; | ||
import { buildSchema } from './util'; | ||
import assert from 'assert'; | ||
|
||
jest.useFakeTimers(); | ||
jest.spyOn(global, 'setTimeout'); | ||
|
||
const cache = new Map<string, string>() | ||
|
||
const cacheCallback = { | ||
has: jest.fn((key: string) => Promise.resolve(cache.has(key))), | ||
get: jest.fn((key: string) => Promise.resolve(cache.get(key))), | ||
delete: jest.fn((key: string) => Promise.resolve(cache.delete(key))), | ||
set: jest.fn(async (key: string, value: string) => { | ||
Promise.resolve(cache.set(key, value)) | ||
}), | ||
} | ||
|
||
const { cacheDirectiveTypeDefs, cacheDirectiveTransformer } = cacheDirective('cache', cacheCallback) | ||
|
||
describe('@cache directive', () => { | ||
let testServer: ApolloServer; | ||
|
||
const resolvers = { | ||
Query: { | ||
user: () => ({ | ||
age: 28 | ||
}) | ||
}, | ||
}; | ||
|
||
const testQuery = ` | ||
query ExampleQuery { | ||
user { | ||
age | ||
} | ||
} | ||
` | ||
|
||
afterEach(async () => { | ||
if (testServer) { | ||
await testServer.stop() | ||
} | ||
}) | ||
|
||
it('will cache a field value before returning a response with correct ttl', async () => { | ||
const ttl = 8000 | ||
const schema = buildSchema({ | ||
typeDefs: [ | ||
`type User { | ||
age: Int @cache(key: "user_age", ttl: ${ttl}) | ||
} | ||
type Query { | ||
user: User | ||
} | ||
`, | ||
cacheDirectiveTypeDefs, | ||
], | ||
resolvers, | ||
transformers: [cacheDirectiveTransformer], | ||
}) | ||
|
||
testServer = new ApolloServer({ schema }) | ||
|
||
const response = await testServer.executeOperation<{ user: { age: number } }>({ | ||
query: testQuery | ||
}) | ||
|
||
assert(response.body.kind === 'single'); | ||
expect(response.body.singleResult.errors).toBeUndefined(); | ||
expect(response.body.singleResult.data.user.age).toEqual(28); | ||
expect(setTimeout).toHaveBeenCalledTimes(1); | ||
expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), ttl); | ||
expect(cacheCallback.set).toHaveBeenCalled() | ||
}) | ||
|
||
it('will delete a cache field value if the ttl has long expired', async () => { | ||
const ttl = 3000 | ||
const key = 'user_age' | ||
const schema = buildSchema({ | ||
typeDefs: [ | ||
`type User { | ||
age: Int @cache(key: "${key}", ttl: ${ttl}) | ||
} | ||
type Query { | ||
user: User | ||
} | ||
`, | ||
cacheDirectiveTypeDefs, | ||
], | ||
resolvers, | ||
transformers: [cacheDirectiveTransformer], | ||
}) | ||
|
||
testServer = new ApolloServer({ schema }) | ||
|
||
const response = await testServer.executeOperation<{ user: { age: number } }>({ | ||
query: testQuery | ||
}) | ||
|
||
assert(response.body.kind === 'single'); | ||
expect(response.body.singleResult.errors).toBeUndefined(); | ||
expect(response.body.singleResult.data.user.age).toEqual(28); | ||
|
||
expect(cacheCallback.set).toHaveBeenCalled() | ||
expect(cacheCallback.set).toHaveBeenCalledWith(key, JSON.stringify(response.body.singleResult.data.user.age)) | ||
|
||
jest.advanceTimersByTime(ttl + 5000) | ||
|
||
expect(cacheCallback.delete).toHaveBeenCalled() | ||
expect(cacheCallback.delete).toHaveBeenCalledWith(key) | ||
}) | ||
}) |