@ureq/lib-hash
v0.0.3
Published
Hash utilities for universal request library
Readme
@ureq/lib-hash
哈希工具库,提供请求哈希和字符串哈希功能。
安装
npm install @ureq/lib-hash
# 或
pnpm add @ureq/lib-hash注意:通常作为
@ureq/business的依赖自动安装,无需单独安装
使用
import { DefaultHashService } from '@ureq/lib-hash';
const hashService = new DefaultHashService();
// 生成请求哈希
const requestHash = hashService.generateRequestHash(
'GET',
'/api/users',
null,
{ params: { page: 1 } }
);
// 生成字符串哈希
const strHash = hashService.hashString('some-string');API
DefaultHashService
class DefaultHashService implements HashService {
generateRequestHash(
method: string,
url: string,
data?: any,
options?: RequestOptions
): string;
hashString(str: string): string;
}功能
generateRequestHash
生成请求的唯一哈希值,用于:
- 请求去重(幂等性保证)
- 缓存键生成
- 请求标识
const hash1 = hashService.generateRequestHash('GET', '/users', null, { params: { page: 1 } });
const hash2 = hashService.generateRequestHash('GET', '/users', null, { params: { page: 1 } });
console.log(hash1 === hash2); // true - 相同的请求生成相同的哈希hashString
生成字符串的哈希值。
const hash = hashService.hashString('hello world');
console.log(hash); // 生成的哈希值哈希算法
默认使用简单的字符串哈希算法,适用于大多数场景。如需更强的哈希算法,可以自定义实现:
import { HashService } from '@ureq/business';
import crypto from 'crypto';
class CryptoHashService implements HashService {
generateRequestHash(method: string, url: string, data?: any, options?: any): string {
const str = JSON.stringify({ method, url, data, options });
return this.hashString(str);
}
hashString(str: string): string {
return crypto.createHash('sha256').update(str).digest('hex');
}
}使用场景
请求去重
import { Request } from '@ureq/core';
import { FetchRequestor } from '@ureq/impl-fetch';
import { DefaultHashService } from '@ureq/lib-hash';
const hashService = new DefaultHashService();
const request = new Request(
new FetchRequestor(),
{
idempotent: {
hashService,
dedupeTime: 1000
}
}
);缓存键生成
const request = new Request(
new FetchRequestor(),
{
cache: {
getCacheKey: (url, options) => {
return hashService.generateRequestHash('GET', url, null, options);
}
}
}
);文档
查看完整文档:https://sunny-117.github.io/ureq
License
MIT
