@snail-js/api 0.1.14 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +223 -73
  2. package/README_EN.md +592 -0
  3. package/dist/cache/index.d.ts +6 -2
  4. package/dist/cache/indexDBCache.d.ts +7 -22
  5. package/dist/cache/localstorageCache.d.ts +7 -22
  6. package/dist/cache/memoryCache.d.ts +8 -23
  7. package/dist/core/index.d.ts +4 -1
  8. package/dist/core/snailApi.d.ts +22 -0
  9. package/dist/core/snailMethod.d.ts +54 -0
  10. package/dist/core/snailServer.d.ts +34 -0
  11. package/dist/core/snailSse.d.ts +20 -0
  12. package/dist/decorators/api.d.ts +9 -9
  13. package/dist/decorators/{param.d.ts → args.d.ts} +6 -0
  14. package/dist/decorators/cache.d.ts +11 -6
  15. package/dist/decorators/sse.d.ts +2 -3
  16. package/dist/decorators/strategy.d.ts +1 -1
  17. package/dist/index.d.ts +2 -2
  18. package/dist/snail-api.js +1125 -531
  19. package/dist/snail-api.umd.cjs +1126 -532
  20. package/dist/typings/api.option.d.ts +16 -0
  21. package/dist/typings/apiProxy.d.ts +5 -4
  22. package/dist/typings/cache.management.option.d.ts +16 -10
  23. package/dist/typings/cache.type.d.ts +17 -2
  24. package/dist/typings/index.d.ts +2 -1
  25. package/dist/typings/request.method.d.ts +9 -8
  26. package/dist/typings/response.data.d.ts +7 -3
  27. package/dist/typings/snail.method.d.ts +11 -0
  28. package/dist/typings/snail.option.d.ts +5 -1
  29. package/dist/typings/sse.d.ts +5 -1
  30. package/dist/typings/versioning.option.d.ts +2 -2
  31. package/dist/utils/function.d.ts +29 -8
  32. package/dist/versioning/index.d.ts +1 -0
  33. package/dist/versioning/versioning.d.ts +10 -5
  34. package/package.json +2 -1
  35. package/dist/core/snail.d.ts +0 -32
  36. package/dist/typings/api.config.d.ts +0 -9
package/README_EN.md ADDED
@@ -0,0 +1,592 @@
1
+ <p>
2
+ <img src="https://img.shields.io/badge/TypeScript-1e80ff"></img>
3
+ <img src="https://img.shields.io/npm/v/axios?label=axios&labelColor=1e80ff&color=67C23A"></img>
4
+ <img src="https://img.shields.io/npm/v/reflect-metadata?label=reflect-metadata&labelColor=1e80ff&color=67C23A"></img>
5
+ </p>
6
+
7
+ <a href='./README.md'>中文文档</a>|English Document
8
+
9
+ ## Project Introduction
10
+
11
+ - Secondary encapsulation based on Axios
12
+ - Use `reflect-metadata` to create and process metadata
13
+ - Provide decorators to define request methods, supporting all HTTP methods and SSE
14
+
15
+ ## Installation
16
+
17
+ `npm install @snail-js/api`
18
+
19
+ ## Usage
20
+
21
+ 1. Enable TypeScript decorator configuration:
22
+
23
+ ```json
24
+ // tsconfig.json
25
+ {
26
+ "module": "ESNext",
27
+ // Module resolution strategy
28
+ "moduleResolution": "node",
29
+ "baseUrl": ".",
30
+ // Target must be higher than ES6
31
+ "target": "ESNext",
32
+ // lib should include ES versions above ES6
33
+ "lib": ["ESNext", "DOM"],
34
+ // Include reflect-metadata types
35
+ "types": ["reflect-metadata"],
36
+ "emitDecoratorMetadata": true,
37
+ "experimentalDecorators": true,
38
+
39
+ "skipLibCheck": true,
40
+ "strictNullChecks": false
41
+ }
42
+ ```
43
+
44
+ 2. Create Snail backend configuration instance:
45
+
46
+ ```ts
47
+ // service.ts
48
+ import { SnailServer, Server } from "@snail-js/api";
49
+
50
+ @Server({
51
+ baseURL: "/api",
52
+ timeout: 5000,
53
+ })
54
+ class BackEnd extends SnailServer {}
55
+
56
+ export const Service = new BackEnd();
57
+ ```
58
+
59
+ 3. Create API instance:
60
+
61
+ ```ts
62
+ // user.ts
63
+ import { Api, Get, Post, Query, Data, SnailApi } from "@snail-js/api";
64
+ import { Service } from "./service";
65
+
66
+ @Api("user")
67
+ class UserApi extends SnailApi {
68
+ @Get()
69
+ get(@Query("id") id: string) {}
70
+
71
+ @Post()
72
+ create(@Data() user: User) {}
73
+ }
74
+ // Create and export API
75
+ export const userApi = Service.createApi(UserApi);
76
+ ```
77
+
78
+ 4. Send requests:
79
+
80
+ ```ts
81
+ import { userApi } from "./user";
82
+
83
+ const getUser = await userApi.get("1");
84
+ const { send, onSuccess, onError, onHitCache, on } = getUser;
85
+ const data = await send();
86
+ ```
87
+
88
+ ## `SnailMethod` Instance
89
+
90
+ - When calling `Service.createApi(ApiInstance)`, creates a proxy for methods decorated with `RequestMethod` (e.g. @Get, @Post)
91
+ - Returns a function containing request parameters, which when called returns a `SnailMethod` instance
92
+
93
+ ### `SnailMethod` Methods
94
+
95
+ - `send`: Send request
96
+ _Async function that executes the current request_
97
+ - `onSuccess`: Request success callback
98
+ _Register success event handler_
99
+ - `onError`: Request failure callback
100
+ _Register error event handler_
101
+ - `onHitCache`: Cache hit callback
102
+ _Register cache hit event handler_
103
+ - `onFinish`: Request completion callback
104
+ _Register completion event handler (fires on both success/error)_
105
+ - `on`: Event listener
106
+ _Register custom event handlers_
107
+ _Register custom event handlers_
108
+ - `emit`: Trigger custom events
109
+ _Emit custom events_
110
+ - `off`: Remove event listeners
111
+ _Unregister custom event handlers_
112
+
113
+ ### `SnailMethod` Properties
114
+ - `response`: AxiosResponse - Raw response object
115
+ - `request`: AxiosRequestConfig - Final processed request after applying Versioning and Strategies
116
+ - `version`: string - Effective request version (undefined if Versioning disabled)
117
+ - `name`: string - Full method identifier in `ServerName.ApiName.MethodName` format
118
+ - `error`: Error | null - Error object if request failed, null otherwise
119
+
120
+ ### Server Configuration
121
+
122
+ <table>
123
+ <tr>
124
+ <th>Option</th>
125
+ <th>Type</th>
126
+ <th>Required</th>
127
+ <th>Default Value</th>
128
+ <th>Description</th>
129
+ </tr>
130
+ <tr>
131
+ <td>name</td>
132
+ <td>string</td>
133
+ <td>No</td>
134
+ <td>Class name inheriting SnailServer</td>
135
+ <td>Unique server identifier</td>
136
+ </tr>
137
+ <tr>
138
+ <td>baseUrl</td>
139
+ <td>string</td>
140
+ <td>No</td>
141
+ <td>'\'</td>
142
+ <td>API prefix (same as axios baseURL)</td>
143
+ </tr>
144
+ <tr>
145
+ <td>Versioning</td>
146
+ <td><a href="#versioningoption">VersioningOption</a></td>
147
+ <td>No</td>
148
+ <td>undefine</td>
149
+ <td>Versioning configuration</td>
150
+ </tr>
151
+ <tr>
152
+ <td>timeout</td>
153
+ <td>number</td>
154
+ <td>No</td>
155
+ <td>5000</td>
156
+ <td>Global timeout (ms)</td>
157
+ </tr>
158
+ <tr>
159
+ <td>cacheManage</td>
160
+ <td>{type:CacheType,ttl:number}</td>
161
+ <td>No</td>
162
+ <td>{
163
+ type: CacheType.Memory,
164
+ ttl: 500
165
+ }</td>
166
+ <td>Cache manager (ttl in seconds)</td>
167
+ </tr>
168
+ <tr>
169
+ <td>cacheFor</td>
170
+ <td>RequestMethod | RequestMethod[] | 'All' | 'all' </td>
171
+ <td>No</td>
172
+ <td>Get</td>
173
+ <td>Methods to enable caching</td>
174
+ </tr>
175
+ <tr>
176
+ <td>enableLog</td>
177
+ <td>boolean</td>
178
+ <td>No</td>
179
+ <td>false</td>
180
+ <td>Enable debug logs</td>
181
+ </tr>
182
+ </table>
183
+
184
+ ### API Configuration
185
+ - Decorate API classes with `@Api()` and extend `SnailApi`
186
+
187
+ <table>
188
+ <tr>
189
+ <th>Option</th>
190
+ <th>Type</th>
191
+ <th>Required</th>
192
+ <th>Default Value</th>
193
+ <th>Description</th>
194
+ </tr>
195
+ <tr>
196
+ <td>name</td>
197
+ <td>string</td>
198
+ <td>No</td>
199
+ <td>default use extends`SnailApi` class name</td>
200
+ <td>Unique API identifier</td>
201
+ </tr>
202
+ <tr>
203
+ <td>timeout</td>
204
+ <td>number</td>
205
+ <td>No</td>
206
+ <td></td>
207
+ <td>Overrides server timeout</td>
208
+ </tr>
209
+ <tr>
210
+ <td>version</td>
211
+ <td>string</td>
212
+ <td>No</td>
213
+ <td></td>
214
+ <td>Overrides server defaultVersion</td>
215
+ </tr>
216
+ </table>
217
+
218
+ ## Request Method Decorators
219
+ - Used in API classes to mark request methods
220
+ - Supports all axios methods: Get, Post, Head, Put, Delete, Patch, Options
221
+ - Parameter: path?: string - Endpoint path (combined with baseURL)
222
+
223
+ ## Parameter Decorators
224
+ ### Query Parameters @Query
225
+ - @Query(key?:string)
226
+ Example:
227
+
228
+ ```ts
229
+ @Api("user")
230
+ class UserApi {
231
+ @Get()
232
+ get(@Query("id") id: string, @Query("sign") sign: string) {}
233
+ }
234
+ ```
235
+ > Parameters will be appended as ?k1=v1&k2=v2
236
+
237
+ ### Route Parameters @Params
238
+ - @Params(key?:string)
239
+ Example with object:
240
+ ```ts
241
+ class RouteParams {
242
+ id: string;
243
+ sign: string;
244
+ }
245
+
246
+ @Api("user/:id/:sign")
247
+ class UserApi {
248
+ @Get()
249
+ get(@Params() params: RouteParams) {}
250
+ }
251
+ ```
252
+
253
+ > Automatically maps object properties to route parameters
254
+
255
+ ### Request Data
256
+
257
+ - `@Data(key?:string)`
258
+ - Usage pattern same as `@Params`, supports mixed usage
259
+
260
+ ## Strategy Decorator `@UseStrategy`
261
+
262
+ - `@UseStrategy(...Strategy[])`
263
+
264
+ ### Request Strategy
265
+
266
+ - Executed before request sending, subsequent strategy results override previous ones
267
+ - If returns processed request, uses it for sending; otherwise uses original or previous strategy's result
268
+
269
+ ```typescript
270
+ class CustomStrategy extends Strategy {
271
+ applyRequest(request: AxiosRequestConfig) {
272
+ request.headers["Access-Token"] = "abcde";
273
+ return request;
274
+ }
275
+ }
276
+
277
+ // Applied to Snail for global request strategies
278
+ @Server({
279
+ baseURL: "/api",
280
+ timeout: 5000,
281
+ })
282
+ @UseStrategy(CustomStrategy)
283
+ class BackEnd extends Snail<ShanheResponse> {}
284
+ export const Service = new BackEnd();
285
+ // Register strategy after instance creation
286
+ Service.registerStrategies(CustomStrategy);
287
+
288
+ // Applied to API for method-specific strategies
289
+ @Api("test")
290
+ @UseStrategy(CustomStrategy)
291
+ class Test {}
292
+ const TestApi = Service.createApi(Test);
293
+ TestApi.registerStrategies(CustomStrategy);
294
+
295
+ // Applied to method for endpoint-level strategies
296
+ @Api("test")
297
+ @UseStrategy(CustomStrategy)
298
+ class Test {
299
+ @Get()
300
+ @UseStrategy(CustomStrategy)
301
+ get() {}
302
+ }
303
+ // Register strategy before request
304
+ const TestApi = Service.createApi(Test);
305
+ const getSomething = TestApi.get();
306
+ getSomething.registerStrategies(CustomStrategy);
307
+ { send, registerStrategies } = getSomething;
308
+ ```
309
+
310
+ ### Response Strategy
311
+ - Executed after receiving server response
312
+ - Processed response propagates through strategy chain
313
+
314
+ ```typescript
315
+ class CustomStrategy extends Strategy {
316
+ applyResponse(response: AxiosResponse) {
317
+ const { status } = response;
318
+ if (status == 200) {
319
+ // Custom processing
320
+ }
321
+ return response;
322
+ }
323
+ }
324
+ ```
325
+
326
+ ## Version Management Decorators @Versioning & @Version
327
+ ### Version Manager @Versioning(VersioningOption)
328
+ - Global version management
329
+
330
+ ```typescript
331
+ @Server({
332
+ baseURL: "/api",
333
+ timeout: 5000,
334
+ })
335
+ @Versioning({
336
+ type: VersioningType.Header,
337
+ defaultVersion: "0.1.0",
338
+ })
339
+ class BackEnd extends Snail<ShanheResponse> {}
340
+
341
+ export const Service = new BackEnd();
342
+ ```
343
+
344
+ ### <a id='versioningOption'>VersioningOption Type</a>
345
+
346
+ ```typescript
347
+ export enum VersioningType {
348
+ Uri,
349
+ Header,
350
+ Query,
351
+ Custom,
352
+ }
353
+
354
+ interface VersioningCommonOption {
355
+ defaultVersion: string;
356
+ }
357
+
358
+ export interface VersioningUriOption extends VersioningCommonOption {
359
+ type: VersioningType.Uri;
360
+ prefix?: string;
361
+ }
362
+
363
+ export interface VersioningHeaderOption extends VersioningCommonOption {
364
+ type: VersioningType.Header;
365
+ header?: string;
366
+ }
367
+
368
+ export interface VersioningQueryOption extends VersioningCommonOption {
369
+ type: VersioningType.Query;
370
+ key?: string;
371
+ }
372
+
373
+ export interface VersioningCustomOption extends VersioningCommonOption {
374
+ type: VersioningType.Custom;
375
+ extractor: (requestOptions: unknown) => {
376
+ url: string;
377
+ headers: Record<string, any>;
378
+ };
379
+ }
380
+
381
+ export type VersioningOption =
382
+ | VersioningUriOption
383
+ | VersioningHeaderOption
384
+ | VersioningQueryOption
385
+ | VersioningCustomOption;
386
+ ```
387
+
388
+ ### Temporary Version Modifier @Version
389
+ - Override version for specific methods
390
+ ```typescript
391
+ @Api("test")
392
+ class Test {
393
+ @Get("HelloWorld")
394
+ @Version("0.2.0")
395
+ test() {}
396
+ }
397
+ ```
398
+
399
+ > Enables temporary version override for testing
400
+
401
+ ### Cache Decorator @HitSource
402
+ - @HitSource(name:string)
403
+ - Defines cache invalidation sources
404
+ - Name format: serverName:apiName:methodName
405
+ > Note: Use configured names if available, otherwise class names
406
+
407
+ ```typescript
408
+ @Api("test",{name:'api1'})
409
+ @HitSource("api1")
410
+ class Test {
411
+ @Get("HelloWorld")
412
+ @HitSource("api1.test2")
413
+ test1() {}
414
+
415
+ @Post()
416
+ test2() {}
417
+
418
+ @Get()
419
+ // Invalidates cache for all Test class methods
420
+ @HitSource("api1")
421
+ test3() {}
422
+ }
423
+ ```
424
+
425
+ > Successful [Post]test calls invalidate [Get]test/HelloWorld cache Default caching only for GET methods. Use @Server({cacheFor:'all'}) for other methods
426
+
427
+ > When `test3` method request succeeds, it won't be cached
428
+
429
+ > Note: To enable caching, configure `@Server({cacheManage})` cache manager
430
+
431
+ ### Upload Progress Decorator `@UploadProgress`
432
+
433
+ - `@UploadProgress((progressEvent: AxiosProgressEvent) => void)`
434
+
435
+ ### Download Progress Decorator `@DownloadProgress`
436
+
437
+ - `@DownloadProgress((progressEvent: AxiosProgressEvent) => void)`
438
+
439
+ ## Server-Sent Events (SSE)
440
+
441
+ ### Create SSE Endpoint
442
+
443
+ ```typescript
444
+ @Sse("sse")
445
+ class ServerSend extends SnailSse {
446
+
447
+ @OnSseOpen()
448
+ handleOpen(event: Event) {
449
+ console.log("SSE connection opened:", event);
450
+ }
451
+
452
+ @OnSseError()
453
+ handleError(event: Event) {
454
+ console.log("SSE error occurred:", event);
455
+ }
456
+
457
+ // Handle default message events
458
+ @SseEvent()
459
+ handleEvent(event: MessageEvent) {
460
+ console.log("SSE message event:", event.data);
461
+ }
462
+
463
+ // Handle custom named events
464
+ @SseEvent("chunk")
465
+ handleChunkEvent(event: Event) {
466
+ console.log("SSE chunk event:", event);
467
+ }
468
+ }
469
+
470
+ export const Sse = Service.createSse(ServerSend);
471
+ ```
472
+
473
+ ### SSE Decorator @Sse
474
+ - @Sse(path: string, options?: { withCredentials?: boolean, version?: string })
475
+ - Creates a server-sent events connection, returns a function to open SSE connection:
476
+ - Returns { eventSource: EventSource, close: () => void } when called:
477
+ - eventSource: SSE connection instance
478
+ - close: Method to close the connection
479
+ ### SSE Open Handler Decorator @OnSseOpen
480
+ - Registers decorated method as onopen handler for EventSource instances created by @Sse decorated methods
481
+ ### SSE Error Handler Decorator @OnSseError
482
+ - Registers decorated method as onerror handler for EventSource instances created by @Sse decorated methods
483
+ ### SSE Event Handler Decorator @SseEvent
484
+ - @SseEvent(eventName?: string)
485
+ - Without eventName : Registers as default message event handler
486
+ - With eventName : Registers as handler for specified custom event
487
+
488
+ ------
489
+
490
+ ## TypeScript Support
491
+ ### Default Response Type
492
+
493
+ ```typescript
494
+ export type StandardResponseData<
495
+ T extends ResponseJsonData = Record<string, any>
496
+ > = {
497
+ code: number;
498
+ message: string;
499
+ data: T;
500
+ };
501
+ ```
502
+
503
+ ### Custom Response Types
504
+ 1. Define backend response format:
505
+ ```typescript
506
+ export class CustomResponse {
507
+ status_code: number;
508
+ msg: string;
509
+ }
510
+ ```
511
+ 2. Apply type when creating service:
512
+ ```typescript
513
+ // service.ts
514
+ import { SnailServer, Server } from "@snail-js/api";
515
+
516
+ @Server({
517
+ baseURL: "/api",
518
+ timeout: 5000,
519
+ })
520
+ class BackEnd extends SnailServer<CustomResponse> {}
521
+
522
+ export const Service = new BackEnd();
523
+ ```
524
+
525
+ 3. Type annotation when calling APIs:
526
+ ```typescript
527
+ import { userApi } from "./user";
528
+
529
+ class User {
530
+ id: number;
531
+ name: string;
532
+ tel: string;
533
+ age: number;
534
+ }
535
+
536
+ const getUser = userApi.get<User>("1");
537
+ const { send } = getUser;
538
+
539
+ const res = await send();
540
+
541
+ // Default data key:
542
+ // res.data => CustomResponse & { data: User }
543
+ ```
544
+
545
+ > API response format:
546
+ ```typescript
547
+ const getUser = userApi.get<User>("1");
548
+ const { send } = getUser;
549
+ const res = await send();
550
+
551
+ // res.data => CustomResponse & { data: User }
552
+
553
+ const getUser = userApi.get<Blob>("1");
554
+ const { send } = getUser;
555
+ const res = await send();
556
+ // res => AxiosResponse<Blob>
557
+ ```
558
+
559
+ 4. Custom data key configuration:
560
+
561
+ ```typescript
562
+ @Server({
563
+ baseURL: "/api",
564
+ timeout: 5000,
565
+ })
566
+ class BackEnd extends Snail<CustomResponse, "record"> {}
567
+
568
+ const { send } = userApi.get<User>("1");
569
+ const res = await send();
570
+ // Custom data key:
571
+ // res.data => CustomResponse & { record: User }
572
+ ```
573
+
574
+ ### Non-JSON Responses
575
+ - For non-JSON content-type responses: send() returns AxiosResponse
576
+ - For JSON content-type responses: send() returns AxiosResponse.data
577
+
578
+ ### Repository
579
+ <p>
580
+ <a href="https://gitee.com/limich/snail">
581
+ <img src="https://img.shields.io/badge/snail-js?style=flat&label=gitee&labelColor=F56C6C&link=https%3A%2F%2Fgitee.com%2Flimich%2Fsnail"></img>
582
+ </a>
583
+ </p>
584
+ <p>
585
+ <a href="https://github.com/limingchang/snail">
586
+ <img src="https://img.shields.io/badge/snail-js?style=flat&label=github&labelColor=F56C6C&link=https%3A%2F%2Fgihub.com%2Flimingchang%2Fsnail"></img>
587
+ </a>
588
+ </p>
589
+
590
+ ### Author
591
+
592
+ - mc.lee
@@ -1,5 +1,9 @@
1
1
  import MemoryCache from "./memoryCache";
2
2
  import LocalStorageCache from "./localstorageCache";
3
3
  import IndexDBCache from "./indexDBCache";
4
- import { CacheType } from "../typings";
5
- export declare function createCache(type: CacheType, ttl: number): LocalStorageCache | IndexDBCache | MemoryCache | undefined;
4
+ import { CacheStorageAdapter, CacheStorage, MemoryCacheOption, IndexDBCacheOption, LocalStorageCacheOption, CustomCacheOption, CacheManagementOption } from "../typings";
5
+ export declare function createCache<T extends CacheManagementOption>(options: T): CacheStorage;
6
+ export declare function createCache<T extends MemoryCacheOption>(optios: T): MemoryCache;
7
+ export declare function createCache<T extends LocalStorageCacheOption>(optios: T): LocalStorageCache;
8
+ export declare function createCache<T extends IndexDBCacheOption>(optios: T): IndexDBCache;
9
+ export declare function createCache<T extends CustomCacheOption>(optios: T): CacheStorageAdapter;
@@ -1,28 +1,13 @@
1
- export default class IndexDBCache {
1
+ import { CacheGetData, CacheStorageAdapter } from "../typings";
2
+ export default class IndexDBCache implements CacheStorageAdapter {
2
3
  ttl: number;
3
4
  private db?;
4
5
  constructor(ttl: number);
5
6
  init(): Promise<void>;
6
7
  private openDB;
7
- get<T = any>(key: string): Promise<{
8
- error: null;
9
- data: T;
10
- } | {
11
- error: any;
12
- data: null;
13
- }>;
14
- set<T = any>(key: string, value: T): Promise<{
15
- error: null;
16
- data: true;
17
- } | {
18
- error: any;
19
- data: null;
20
- }>;
21
- delete(key: string): Promise<{
22
- error: null;
23
- data: true;
24
- } | {
25
- error: any;
26
- data: null;
27
- }>;
8
+ get<T = any>(key: string): Promise<CacheGetData<T>>;
9
+ set<T = any>(key: string, value: T): Promise<boolean>;
10
+ delete(key: string): Promise<boolean>;
11
+ clear(): Promise<boolean>;
12
+ keys(): Promise<string[]>;
28
13
  }
@@ -1,25 +1,10 @@
1
- export default class LocalStorageCache {
1
+ import { CacheGetData, CacheStorageAdapter } from "../typings";
2
+ export default class LocalStorageCache implements CacheStorageAdapter {
2
3
  ttl: number;
3
4
  constructor(ttl: number);
4
- get<T = any>(key: string): Promise<{
5
- error: null;
6
- data: T;
7
- } | {
8
- error: any;
9
- data: null;
10
- }>;
11
- set<T = any>(key: string, value: T): Promise<{
12
- error: null;
13
- data: true;
14
- } | {
15
- error: any;
16
- data: null;
17
- }>;
18
- delete(key: string): Promise<{
19
- error: null;
20
- data: true;
21
- } | {
22
- error: any;
23
- data: null;
24
- }>;
5
+ get<T = any>(key: string): Promise<CacheGetData<T>>;
6
+ set<T = any>(key: string, value: T): Promise<boolean>;
7
+ delete(key: string): Promise<boolean>;
8
+ clear(): Promise<boolean>;
9
+ keys(): Promise<string[]>;
25
10
  }
@@ -1,26 +1,11 @@
1
- export default class MemoryCache {
2
- private cache;
1
+ import { CacheGetData, CacheStorageAdapter } from "../typings";
2
+ export default class MemoryCache implements CacheStorageAdapter {
3
+ private CacheMap;
3
4
  ttl: number;
4
5
  constructor(ttl: number);
5
- get<T = any>(key: string): Promise<{
6
- error: null;
7
- data: T;
8
- } | {
9
- error: any;
10
- data: null;
11
- }>;
12
- set<T = any>(key: string, value: T): Promise<{
13
- error: null;
14
- data: true;
15
- } | {
16
- error: any;
17
- data: null;
18
- }>;
19
- delete(key: string): Promise<{
20
- error: null;
21
- data: true;
22
- } | {
23
- error: any;
24
- data: null;
25
- }>;
6
+ get<T = any>(key: string): Promise<CacheGetData<T>>;
7
+ set<T = any>(key: string, value: T): Promise<boolean>;
8
+ delete(key: string): Promise<boolean>;
9
+ clear(): Promise<boolean>;
10
+ keys(): Promise<string[]>;
26
11
  }