核心缓存库
概览
缓存库的核心包提供了创建缓存执行的基础界面和厂房模式. 它定义了所有缓存适配器必须遵守的合同,确保了与不同缓存策略互动的一致API.
福利
- 统一接口:所有缓存执行都符合相同的接口,使其之间容易切换.
- 工厂模式:工厂模式允许基于配置的动态创建缓存实例.
接口
快取界面
这个 CacheInterface 定义所有缓存执行必须执行的方法:
set(key: string, value: TypeValue, expiresAfter?: number): Promise<boolean>get(key: string): Promise<TypeValue | undefined>delete(key: string): Promise<boolean>has(key: string): Promise<boolean>
快取 Factory 界面
这个 CacheFactoryInterface 定义创建缓存实例的方法 :
createCache(config: TypeConfig): Promise<CacheInterface>
使用量
为了使用这些核心职能,遵循这些步骤:
- 从核心包中导入必要的接口和工厂.
- 通过扩展自定义缓存适配器执行
CacheInterface。 。 。 . - 创建执行
CacheFactoryInterface。 。 。 .
示例
import { CacheInterface, CacheFactoryInterface } from '@cachehub/core';
class MyCustomCache implements CacheInterface {
// Implement the required methods: set, get, delete, has
}
class MyCustomCacheFactory implements CacheFactoryInterface {
public async createCache(config: any): Promise<CacheInterface> {
return new MyCustomCache();
}
}
让你的包裹自我登记 确保你的包裹 与工厂登记 CacheFactoryRegistry 并导出工厂类作为默认导出单位 index.ts。例如:
import { CacheFactoryRegistry } from '@cachehub/core';
import { MyCustomCacheFactory } from './Factory';
CacheFactoryRegistry.registerCacheFactory('my-custom-cache', MyCustomCacheFactory);
// default export so that core factory can use it directly
export default MyCustomCacheFactory;
一般类型使用
CacheInterface 支持用于类型安全存储和取值的通用类型. 以下是使用缓存方法的通用名的例子:
// Using primitive types
await cache.set<string>('stringKey', 'value');
const stringValue = await cache.get<string>('stringKey');
await cache.set<number>('numberKey', 42);
const numberValue = await cache.get<number>('numberKey');
await cache.set<boolean>('booleanKey', true);
const booleanValue = await cache.get<boolean>('booleanKey');
// Using complex objects
interface User {
id: number;
name: string;
email: string;
}
const user: User = {
id: 1,
name: 'John Doe',
email: '[email protected]'
};
await cache.set<User>('userKey', user);
const userValue = await cache.get<User>('userKey');
// Using arrays
await cache.set<string[]>('arrayKey', ['a', 'b', 'c']);
const arrayValue = await cache.get<string[]>('arrayKey');
在执行自定义缓存适配器时,确保在执行中妥善处理通用类型,在整个应用程序中保持类型安全.
文件夹结构
每个软件包的文件夹结构通常包括:
src/:包含包的源代码,包括:Factory/:包含用于创建缓存处理器的工厂类.Cache/: 包含执行缓存对象的类.Type/: 包含类型定义和接口.
tests/:包含包件的单位测试.README.md: 包的文档..env: 配置的环境变量.
捐款
欢迎捐款! 随意叉出这个寄存器并提交拉取请求. 在提交之前,请确保您的代码通过所有起伏和单元测试.
您可以使用 :
pnpm format
您可以使用 :
pnpm test