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 Redis and Memcached #1191

Merged
merged 4 commits into from
Jun 19, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions packages/apollo-server-caching-memcached/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.idea
6 changes: 6 additions & 0 deletions packages/apollo-server-caching-memcached/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*
!src/**/*
!dist/**/*
dist/**/*.test.*
!package.json
!README.md
32 changes: 32 additions & 0 deletions packages/apollo-server-caching-memcached/__mocks__/date.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const RealDate = global.Date;

export function mockDate() {
global.Date = new Proxy(RealDate, handler);
}

export function unmockDate() {
global.Date = RealDate;
}

let now = Date.now();

export function advanceTimeBy(ms: number) {
now += ms;
}

const handler = {
construct(target, args) {
if (args.length === 0) {
return new Date(now);
} else {
return new target(...args);
}
},
get(target, propKey, receiver) {
if (propKey === 'now') {
return () => now;
} else {
return target[propKey];
}
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// use mock implementations for underlying databases
jest.mock('memcached', () => require('memcached-mock'));

import MemcachedKeyValueCache from '../src/index';
import { advanceTimeBy, mockDate, unmockDate } from '../__mocks__/date';

describe('Memcached Connector', () => {
let keyValueCache;

beforeAll(() => {
keyValueCache = new MemcachedKeyValueCache('localhost');
mockDate();
});

beforeEach(() => {
keyValueCache.flush();
});

afterAll(() => {
unmockDate();
keyValueCache.close();
});

it('can do a basic get and set', async () => {
await keyValueCache.set('hello', 'world');
expect(await keyValueCache.get('hello')).toBe('world');
expect(await keyValueCache.get('missing')).not.toBeDefined();
});

it('is able to expire keys based on ttl', async () => {
await keyValueCache.set('short', 's', { ttl: 1 });
await keyValueCache.set('long', 'l', { ttl: 5 });
expect(await keyValueCache.get('short')).toBe('s');
expect(await keyValueCache.get('long')).toBe('l');
advanceTimeBy(1500);
expect(await keyValueCache.get('short')).not.toBeDefined();
expect(await keyValueCache.get('long')).toBe('l');
advanceTimeBy(4000);
expect(await keyValueCache.get('short')).not.toBeDefined();
expect(await keyValueCache.get('long')).not.toBeDefined();
});
});
53 changes: 53 additions & 0 deletions packages/apollo-server-caching-memcached/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"name": "apollo-server-caching-memcached",
"version": "2.0.0-rc.0",
"author": "opensource@apollographql.com",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-caching-memcached"
},
"homepage": "https://github.com/apollographql/apollo-server#readme",
"bugs": {
"url": "https://github.com/apollographql/apollo-server/issues"
},
"scripts": {
"clean": "rm -rf lib",
"compile": "tsc",
"prepublish": "npm run clean && npm run compile",
"test": "jest --verbose"
},
"main": "dist/index.js",
"types": "dist/index.d.ts",
"engines": {
"node": ">=6"
},
"dependencies": {
"apollo-server-env": "^2.0.0-rc.0",
"apollo-server-caching": "^2.0.0-rc.0",
"memcached": "^2.2.2"
Copy link
Contributor

Choose a reason for hiding this comment

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

Installing the types for these packages will provide a lot more confidence that we are doing the right thing.

npm install -D @types/memcached

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/redis/index.d.ts
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/memcached/index.d.ts

},
"devDependencies": {
"@types/jest": "^23.0.0",
"jest": "^23.1.0",
"ts-jest": "^22.4.6",
"memcached-mock": "^0.1.0"
},
"jest": {
"testEnvironment": "node",
"transform": {
"^.+\\.(ts|js)$": "ts-jest"
},
"moduleFileExtensions": [
"ts",
"js",
"json"
],
"testRegex": "/__tests__/.*$",
"globals": {
"ts-jest": {
"skipBabel": true
}
}
}
}
39 changes: 39 additions & 0 deletions packages/apollo-server-caching-memcached/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { KeyValueCache } from 'apollo-server-caching';
import Memcached from 'memcached';
import { promisify } from 'util';

export default class MemcachedKeyValueCache implements KeyValueCache {
readonly client;
readonly defaultSetOptions = {
ttl: 300,
};

constructor(serverLocation: Memcached.Location, options?: Memcached.options) {
this.client = new Memcached(serverLocation, options);
// promisify client calls for convenience
this.client.get = promisify(this.client.get).bind(this.client);
this.client.set = promisify(this.client.set).bind(this.client);
this.client.flush = promisify(this.client.flush).bind(this.client);
}

async set(
key: string,
data: string,
options?: { ttl?: number },
): Promise<void> {
const { ttl } = Object.assign({}, this.defaultSetOptions, options);
await this.client.set(key, data, ttl);
}

async get(key: string): Promise<string | undefined> {
return await this.client.get(key);
}

async flush(): Promise<void> {
await this.client.flush();
}

async close(): Promise<void> {
this.client.end();
}
}
16 changes: 16 additions & 0 deletions packages/apollo-server-caching-memcached/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"extends": "../../tsconfig",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"removeComments": true,
"strict": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUnusedParameters": true,
"noUnusedLocals": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/__tests__/*", "**/__mocks__/*"],
"types": ["node", "jest"]
}
1 change: 1 addition & 0 deletions packages/apollo-server-caching-redis/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.idea
6 changes: 6 additions & 0 deletions packages/apollo-server-caching-redis/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*
!src/**/*
!dist/**/*
dist/**/*.test.*
!package.json
!README.md
32 changes: 32 additions & 0 deletions packages/apollo-server-caching-redis/__mocks__/date.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const RealDate = global.Date;

export function mockDate() {
global.Date = new Proxy(RealDate, handler);
}

export function unmockDate() {
global.Date = RealDate;
}

let now = Date.now();

export function advanceTimeBy(ms: number) {
now += ms;
}

const handler = {
construct(target, args) {
if (args.length === 0) {
return new Date(now);
} else {
return new target(...args);
}
},
get(target, propKey, receiver) {
if (propKey === 'now') {
return () => now;
} else {
return target[propKey];
}
},
};
45 changes: 45 additions & 0 deletions packages/apollo-server-caching-redis/__tests__/Redis.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// use mock implementations for underlying databases
jest.mock('redis', () => require('redis-mock'));
jest.useFakeTimers(); // mocks out setTimeout that is used in redis-mock

import RedisKeyValueCache from '../src/index';
import { advanceTimeBy, mockDate, unmockDate } from '../__mocks__/date';

describe('Redis Connector', () => {
let keyValueCache;

beforeAll(() => {
keyValueCache = new RedisKeyValueCache({ host: 'localhost' });
mockDate();
});

beforeEach(() => {
keyValueCache.flush();
});

afterAll(() => {
unmockDate();
keyValueCache.close();
});

it('can do a basic get and set', async () => {
await keyValueCache.set('hello', 'world');
expect(await keyValueCache.get('hello')).toBe('world');
expect(await keyValueCache.get('missing')).not.toBeDefined();
});

it('is able to expire keys based on ttl', async () => {
await keyValueCache.set('short', 's', { ttl: 1 });
await keyValueCache.set('long', 'l', { ttl: 5 });
expect(await keyValueCache.get('short')).toBe('s');
expect(await keyValueCache.get('long')).toBe('l');
advanceTimeBy(1500);
jest.advanceTimersByTime(1500);
expect(await keyValueCache.get('short')).not.toBeDefined();
expect(await keyValueCache.get('long')).toBe('l');
advanceTimeBy(4000);
jest.advanceTimersByTime(4000);
expect(await keyValueCache.get('short')).not.toBeDefined();
expect(await keyValueCache.get('long')).not.toBeDefined();
});
});
53 changes: 53 additions & 0 deletions packages/apollo-server-caching-redis/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"name": "apollo-server-caching-redis",
"version": "2.0.0-rc.0",
"author": "opensource@apollographql.com",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-caching-redis"
},
"homepage": "https://github.com/apollographql/apollo-server#readme",
"bugs": {
"url": "https://github.com/apollographql/apollo-server/issues"
},
"scripts": {
"clean": "rm -rf lib",
"compile": "tsc",
"prepublish": "npm run clean && npm run compile",
"test": "jest --verbose"
},
"main": "dist/index.js",
"types": "dist/index.d.ts",
"engines": {
"node": ">=6"
},
"dependencies": {
"apollo-server-caching": "^2.0.0-rc.0",
"apollo-server-env": "^2.0.0-rc.0",
"redis": "^2.8.0"
},
"devDependencies": {
"@types/jest": "^23.0.0",
"jest": "^23.1.0",
"redis-mock": "^0.27.0",
"ts-jest": "^22.4.6"
},
"jest": {
"testEnvironment": "node",
"transform": {
"^.+\\.(ts|js)$": "ts-jest"
},
"moduleFileExtensions": [
"ts",
"js",
"json"
],
"testRegex": "/__tests__/.*$",
"globals": {
"ts-jest": {
"skipBabel": true
}
}
}
}
46 changes: 46 additions & 0 deletions packages/apollo-server-caching-redis/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { KeyValueCache } from 'apollo-server-caching';
import Redis from 'redis';
import { promisify } from 'util';

export default class RedisKeyValueCache implements KeyValueCache {
readonly client;
readonly defaultSetOptions = {
ttl: 300,
};

constructor(options: Redis.ClientOpts) {
this.client = Redis.createClient(options);
// promisify client calls for convenience
this.client.get = promisify(this.client.get).bind(this.client);
this.client.set = promisify(this.client.set).bind(this.client);
this.client.flushdb = promisify(this.client.flushdb).bind(this.client);
this.client.quit = promisify(this.client.quit).bind(this.client);
}

async set(
key: string,
data: string,
options?: { ttl?: number },
): Promise<void> {
const { ttl } = Object.assign({}, this.defaultSetOptions, options);
await this.client.set(key, data, 'EX', ttl);
}

async get(key: string): Promise<string | undefined> {
const reply = await this.client.get(key);
// reply is null if key is not found
if (reply !== null) {
return reply;
}
return;
}

async flush(): Promise<void> {
await this.client.flushdb();
}

async close(): Promise<void> {
await this.client.quit();
return;
}
}
Loading