// Write a tsd file for the module import { expectType, expectError, expectNotAssignable, expectAssignable } from "tsd"; import { createCache, Cache, createStorage } from "."; import { StorageInterface, StorageMemoryOptions } from "./index.js"; // Testing internal types const storageOptions: StorageMemoryOptions = { size: 1000, }; const cache = createCache(); expectType(cache); const storage = createStorage("memory", storageOptions); expectType(storage); const memoryCache = createCache({ storage: { type: "memory", options: storageOptions, }, }); expectType(memoryCache); const cacheWithTtlAndStale = createCache({ ttl: 1000, stale: 1000, }); expectType(cacheWithTtlAndStale); const cacheClass = new Cache({ ttl: 1000, stale: 1000, storage: createStorage('memory', {}) }); expectType(cacheClass); // Testing Union Types const fetchSomething = async (k: any) => { console.log("query", k); return { k }; }; export type CachedFunctions = { fetchSomething: typeof fetchSomething; fetchSomethingElse: typeof fetchSomething; fetchSomethingElseWithTtlFunction: typeof fetchSomething; }; const unionMemoryCache = createCache({ storage: { type: "memory", options: storageOptions, }, }); expectType(unionMemoryCache); const currentCacheInstance = unionMemoryCache .define("fetchSomething", fetchSomething) .define( "fetchSomethingElse", { ttl: 1000, stale: 1000, references: (args, key, result) => result.k }, fetchSomething ) .define( "fetchSomethingElseWithTtlFunction", { ttl: (result) => (result.k ? 1000 : 5), stale: 1000 }, fetchSomething ) .define( "fetchSomethingElseWithCustomStorage", {storage: {'type': 'memory', options: {size: 10}}, stale: 1000 }, fetchSomething ); expectType(currentCacheInstance.fetchSomething); expectType(currentCacheInstance.fetchSomethingElse); expectType( currentCacheInstance.fetchSomethingElseWithTtlFunction ); expectType( currentCacheInstance.fetchSomethingElseWithCustomStorage ); expectType>(cache.clear()); expectType>(cache.clear("fetchSomething")); expectType>(cache.clear("fetchSomething", "bar")); const result = await currentCacheInstance.fetchSomething("test"); expectType<{ k: any }>(result); await unionMemoryCache.invalidateAll("test:*"); await unionMemoryCache.invalidateAll(["test:1", "test:2", "test:3"], "memory"); // Testing define.func only accepts one argument const fetchFuncSingleArgument = async (args: {k1: string, k2:string}) => { console.log("query", args.k1, args.k2); return { k1: args.k1, k2: args.k2 }; }; const fetchFuncMultipleArguments = async (k1: string, k2:string) => { console.log("query", k1, k2); return { k1, k2 }; }; expectAssignable>(["fetchFuncSingleArgument", fetchFuncSingleArgument]); expectNotAssignable>(["fetchFuncMultipleArguments", fetchFuncMultipleArguments]); // Testing define.opts.references memoryCache.define("fetchFuncSingleArgument", { references: (args, key, result) => { expectType<{ k1: string; k2: string }>(args); return []; } }, fetchFuncSingleArgument);