From 484883ab602b113167d92034c87675fd8dfac488 Mon Sep 17 00:00:00 2001 From: Silas Rech Date: Thu, 20 Jul 2017 17:58:40 +0200 Subject: [PATCH] [catbox] Fix classes (#18072) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [catbox] Fix classes * Class extends Class => Class implements Interface * Add TSLint configuration * Add initial tests (Basically testing if I understood how the tests here work 😏) * Fix tests * Don't set Memory to any --- types/catbox/catbox-tests.ts | 27 ++++++++ types/catbox/index.d.ts | 119 ++++++++++++++++++++++++++--------- types/catbox/tsconfig.json | 5 +- types/catbox/tslint.json | 1 + 4 files changed, 122 insertions(+), 30 deletions(-) create mode 100644 types/catbox/catbox-tests.ts create mode 100644 types/catbox/tslint.json diff --git a/types/catbox/catbox-tests.ts b/types/catbox/catbox-tests.ts new file mode 100644 index 0000000000..565573adad --- /dev/null +++ b/types/catbox/catbox-tests.ts @@ -0,0 +1,27 @@ +import Catbox = require("catbox"); + +const Memory: Catbox.EnginePrototypeOrObject = { + start(callback: Catbox.CallBackNoResult) {}, + stop() {}, + get() {}, + set() {}, + drop() {}, + isReady(): boolean { return true; }, + validateSegmentName(segment: string): null { return null; }, +}; + +const client = new Catbox.Client(Memory, { partition: 'cache' }); + +const cache = new Catbox.Policy({ + expiresIn: 5000, +}, client, 'cache'); + +cache.set('foo', 'bar', 5000, () => {}); + +cache.get('foo', () => {}); + +cache.drop('foo', () => {}); + +cache.isReady(); + +cache.stats(); diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 5dad5af29a..e34059d618 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -6,12 +6,8 @@ import * as Boom from 'boom'; -export interface CallBackNoResult { - (err?: Boom.BoomError): void; -} -export interface CallBackWithResult { - (err: Boom.BoomError | null | undefined, result: T): void; -} +export type CallBackNoResult = (err?: Boom.BoomError) => void; +export type CallBackWithResult = (err: Boom.BoomError | null | undefined, result: T) => void; /** * Client @@ -20,14 +16,44 @@ export interface CallBackWithResult { * * function - a prototype function with the signature function(options). catbox will call new func(options). * * object - a pre instantiated client implementation object. Does not support passing options. * options - the strategy configuration object. Each strategy defines its own configuration options with the following common options: - * * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. + * * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, + * the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. * @see {@link https://github.com/hapijs/catbox#client} */ -export interface Client extends ClientApi { - new(engine: EnginePrototypeOrObject, options: ClientOptions): Client; +export class Client implements ClientApi { + constructor(engine: EnginePrototypeOrObject, options: ClientOptions); + + /** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */ + start(callback: CallBackNoResult): void; + /** stop() - terminates the connection to the cache server. */ + stop(): void; + /** + * get(key, callback) - retrieve an item from the cache engine if found where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned + */ + get(key: CacheKey, callback: CallBackWithResult): CacheItem; + /** + * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: + * * key - a cache key object (see [ICacheKey]). + * * value - the string or object value to be stored. + * * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * * callback - a function with the signature function(err). + */ + set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void; + /** + * drop(key, callback) - remove an item from cache where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err). + */ + drop(key: CacheKey, callback: CallBackNoResult): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */ + isReady(): boolean; + /** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */ + validateSegmentName(segment: string): null | Boom.BoomError; } -type EnginePrototypeOrObject = EnginePrototype | ClientApi; +export type EnginePrototypeOrObject = EnginePrototype | ClientApi; /** * A prototype CatBox engine function @@ -50,7 +76,7 @@ export interface ClientApi { * get(key, callback) - retrieve an item from the cache engine if found where: * * key - a cache key object (see [ICacheKey]). * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned - */ + */ get(key: CacheKey, callback: CallBackWithResult): CacheItem; /** * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: @@ -92,21 +118,52 @@ export interface CachedObject { ttl: number; } -type CacheItem = any; +export type CacheItem = any; export interface ClientOptions { partition: string; } /** - * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. The object is constructed using new Policy(options, [cache, segment]) where: + * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. + * The object is constructed using new Policy(options, [cache, segment]) where: * * options - an object with the IPolicyOptions structure * * cache - a Client instance (which has already been started). * * segment - required when cache is provided. The segment name used to isolate cached items within the cache partition. * @see {@link https://github.com/hapijs/catbox#policy} */ -export interface Policy extends PolicyAPI { - new(options: PolicyOptions, cache: Client, segment: string): Policy; +export class Policy implements PolicyAPI { + constructor(options: PolicyOptions, cache: Client, segment: string); + /** + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. + * * callback - the return function. + */ + get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem; + /** + * set(id, value, ttl, callback) - store an item in the cache where: + * * id - the unique item identifier (within the policy segment). + * * value - the string or object value to be stored. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * callback - a function with the signature function(err). + */ + set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; + /** + * drop(id, callback) - remove the item from cache where: + * * id - the unique item identifier (within the policy segment). + * * callback - a function with the signature function(err). + */ + drop(id: string | {id: string}, callback: CallBackNoResult): void; + /** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */ + ttl(created: number): number; + /** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */ + rules(options: PolicyOptions): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */ + isReady(): boolean; + /** stats - an object with cache statistics */ + stats(): CacheStatisticsObject; } /** @@ -116,7 +173,8 @@ export interface Policy extends PolicyAPI { */ export interface PolicyAPI { /** - * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. * * callback - the return function. */ @@ -125,7 +183,8 @@ export interface PolicyAPI { * set(id, value, ttl, callback) - store an item in the cache where: * * id - the unique item identifier (within the policy segment). * * value - the string or object value to be stored. - * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * This should be set to 0 in order to use the caching rules configured when creating the Policy object. * * callback - a function with the signature function(err). */ set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; @@ -152,9 +211,7 @@ export interface PolicyAPI { * @param cached - null if a valid item was not found in the cache, or IPolicyGetCallbackCachedOptions * @param report - an object with logging information about the generation operation */ -export interface PolicyGetCallback{ - (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog): void; -} +export type PolicyGetCallback = (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog) => void; export interface PolicyGetCallbackCachedOptions { /** item - the cached value. */ @@ -178,14 +235,19 @@ export interface PolicyOptions { /** generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: */ generateFunc?: GenerateFunc; /** - * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: + * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. + * Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: * * stored - the timestamp when the item was stored in the cache (in milliseconds). * * ttl - the remaining time-to-live (not the original value used when storing the object). - */ + */ staleIn?: number | ((stored: number, ttl: number) => number); /** staleTimeout - number of milliseconds to wait before returning a stale value while generateFunc is generating a fresh value. */ staleTimeout?: number; - /** generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. */ + /** + * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. + * When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. + * Set to false to disable timeouts which may cause all get() requests to get stuck forever. + */ generateTimeout?: number | false; /** dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. */ dropOnError?: boolean; @@ -193,7 +255,10 @@ export interface PolicyOptions { generateOnReadError?: boolean; /** generateIgnoreWriteError - if false, an upstream cache write error will be passed back with the generated value when calling the get() method. Defaults to true. */ generateIgnoreWriteError?: boolean; - /** pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. */ + /** + * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. + * Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. + */ pendingGenerateTimeout?: number; } @@ -208,9 +273,7 @@ export interface PolicyOptions { * * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. * @see {@link https://github.com/hapijs/catbox#policy} */ -export interface GenerateFunc { - (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)): void; -} +export type GenerateFunc = (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)) => void; /** * An object with logging information about the generation operation containing the following keys (as relevant): @@ -242,6 +305,6 @@ export interface CacheStatisticsObject { stales: number; /** generates - number of calls to the generate function. */ generates: number; - /** errors - cache operations errors. TODO check this*/ + /** errors - cache operations errors. TODO check this */ errors: number; } diff --git a/types/catbox/tsconfig.json b/types/catbox/tsconfig.json index 3bc13b0278..b04177a675 100644 --- a/types/catbox/tsconfig.json +++ b/types/catbox/tsconfig.json @@ -16,6 +16,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "catbox-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/catbox/tslint.json b/types/catbox/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/catbox/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" }