@snail-js/api 0.1.21 → 0.1.23

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.
package/README.md CHANGED
@@ -60,7 +60,7 @@ export const Service = new BackEnd();
60
60
 
61
61
  ```typescript
62
62
  // user.ts
63
- import { Api, Get, Post, Query, Data,SnailApi } from "@snail-js/api";
63
+ import { Api, Get, Post, Query, Data, SnailApi } from "@snail-js/api";
64
64
 
65
65
  import { Service } from "./service";
66
66
 
@@ -81,40 +81,38 @@ export const userApi = Service.createApi(UserApi);
81
81
  ```typescript
82
82
  import { userApi } from "./user";
83
83
 
84
- const getUser = await userApi.get("1");
85
- const { send, onSuccess, onError, onHitCache, on } = getUser;
86
- const data = await send();
84
+ const { send:getUser, onSuccess, onError, onHitCache } = await userApi.get();
85
+
86
+ const data = await getUser("1");
87
87
  ```
88
88
 
89
89
  ## `SnailMethod` 实例
90
+
90
91
  - 调用`Service.createApi(ApiInstance)`后会为`ApiInstance`内被`RequestMethod`(如:@Get、@Post...)装饰的方法创建一个代理,返回一个函数,此函数包含请求参数,调用此函数返回`SnailMethod` 实例
91
92
 
92
93
  ### `SnailMethod` 实例方法
93
94
 
94
95
  - `send` 发送请求
95
- _异步函数,发送当前请求_
96
+ _异步函数,发送当前请求_
96
97
  - `onSuccess` 请求成功回调
97
- _注册请求成功事件_
98
+ _注册请求成功事件_
98
99
  - `onError` 请求失败回调
99
- _注册请求失败事件_
100
+ _注册请求失败事件_
100
101
  - `onHitCache` 请求命中缓存回调
101
- _注册请求命中缓存事件_
102
+ _注册请求命中缓存事件_
102
103
  - `onFinish` 请求完成回调
103
- _注册请求完成事件_
104
- - `on` 监听事件
105
- _注册自定义事件_
106
- - `emit` 触发事件
107
- _触发自定义事件_
108
- - `off` 取消监听事件
109
- _取消自定义事件监听_
104
+ _注册请求完成事件_
105
+ - `registerStrategies` 注册策略
106
+ _注册方法级策略_
110
107
 
111
108
 
112
109
  ### `SnailMethod` 实例属性
110
+
113
111
  - response : AxiosResponse
114
- - request : AxiosRequestConfig ,最终请求的request,这个request是被Versioning和Strategy处理过的
115
- - version : string,最终请求的版本,如果没有开启Versioning则为undefine
116
- - name : string,完整的SnailMethod名称,格式为`ServerName.ApiName.MethodName`
117
- - error : Error | null,请求失败的错误信息,无错误为null
112
+ - request : AxiosRequestConfig ,最终请求的 request,这个 request 是被 Versioning Strategy 处理过的
113
+ - version : string,最终请求的版本,如果没有开启 Versioning 则为 undefine
114
+ - name : string,完整的 SnailMethod 名称,格式为`ServerName.ApiName.MethodName`
115
+ - error : Error | null,请求失败的错误信息,无错误为 null
118
116
 
119
117
  ### Server 配置
120
118
 
@@ -188,7 +186,8 @@ const data = await send();
188
186
  </table>
189
187
 
190
188
  ### Api 配置
191
- - 请使用`@Api()`装饰自定义Api类并继承`SnailApi`
189
+
190
+ - 请使用`@Api()`装饰自定义 Api 类并继承`SnailApi`
192
191
 
193
192
  <table>
194
193
  <tr>
@@ -305,7 +304,7 @@ class UserApi {
305
304
  ### 请求策略
306
305
 
307
306
  - 在请求发送前执行,后面的策略返回结果会覆盖前面的策略
308
- - 若返回处理后的request,则使用处理后的 request 发送请求,否则使用原始 request 或上一个策略返回的request发送请求
307
+ - 若返回处理后的 request,则使用处理后的 request 发送请求,否则使用原始 request 或上一个策略返回的 request 发送请求
309
308
 
310
309
  ```typescript
311
310
  class CustomStrategy extends Strategy {
@@ -346,15 +345,16 @@ class Test {
346
345
  // 发送请求前注册策略
347
346
  const TestApi = Service.createApi(Test);
348
347
  const getSomething = TestApi.get();
349
- getSomething.registerStrategies(CustomStrategy);
350
348
  { send, registerStrategies } = getSomething;
349
+ getSomething.registerStrategies(CustomStrategy);
350
+
351
351
 
352
352
  ```
353
353
 
354
354
  ### 响应策略
355
355
 
356
356
  - 在收到服务器响应后执行
357
- - 若返回处理后的response,则使用处理后的response进行下一个策略或返回,否则使用原始response或上一个策略返回的response返回
357
+ - 若返回处理后的 response,则使用处理后的 response 进行下一个策略或返回,否则使用原始 response 或上一个策略返回的 response 返回
358
358
 
359
359
  ```typescript
360
360
  // 如何定义
@@ -465,11 +465,11 @@ class Test {
465
465
 
466
466
  - `@HitSource(name:string)`
467
467
  - 为被装饰的方法设置缓存失效源,当设置的名称方法被调用且正常响应时,被装饰的方法缓存失效
468
- - name格式为:`serverName:apiName:methodName`
469
- > 注意:若您配置了SnailServer/SnailApi的name选项,请使用此name作为名称,否则使用类名作为名称
468
+ - name 格式为:`serverName:apiName:methodName`
469
+ > 注意:若您配置了 SnailServer/SnailApi name 选项,请使用此 name 作为名称,否则使用类名作为名称
470
470
 
471
471
  ```typescript
472
- @Api("test",{name:'api1'})
472
+ @Api("test", { name: "api1" })
473
473
  @HitSource("api1")
474
474
  class Test {
475
475
  @Get("HelloWorld")
@@ -487,7 +487,7 @@ class Test {
487
487
  ```
488
488
 
489
489
  > 当请求`[Post]test`成功时,`[Get]test/HelloWorld`的缓存失效
490
- > 默认仅Get方法会进行缓存ing缓存,若要开启其他方法的缓存,请使用`@Server({cacheFor:'all'})`配置
490
+ > 默认仅 Get 方法会进行缓存 ing 缓存,若要开启其他方法的缓存,请使用`@Server({cacheFor:'all'})`配置
491
491
 
492
492
  > `test3`方法请求成功时,不缓存
493
493
 
@@ -611,10 +611,10 @@ class User {
611
611
  age: number;
612
612
  }
613
613
 
614
- const getUser = userApi.get<User>("1");
614
+ const getUser = userApi.get<User>();
615
615
  const { send } = getUser;
616
616
 
617
- const res = await send();
617
+ const res = await send("1");
618
618
 
619
619
  // 默认情况,以data为key存储数据
620
620
  // res.data => CustomResponse & { data : User}
@@ -623,15 +623,15 @@ const res = await send();
623
623
  > API 被调用的返回格式
624
624
 
625
625
  ```typescript
626
- const getUser = userApi.get<User>("1");
626
+ const getUser = userApi.get<User>();
627
627
  const { send } = getUser;
628
- const res = await send();
628
+ const res = await send("1");
629
629
 
630
630
  // res.data => CustomResponse & { data: User }
631
631
 
632
- const getUser = userApi.get<Blob>("1");
632
+ const getUser = userApi.get<Blob>();
633
633
  const { send } = getUser;
634
- const res = await send();
634
+ const res = await send("1");
635
635
  // res => AxiosResponse<Blob>
636
636
  ```
637
637
 
@@ -648,16 +648,17 @@ const res = await send();
648
648
  baseURL: "/api",
649
649
  timeout: 5000,
650
650
  })
651
- class BackEnd extends Snail<CustomResponse, "record"> {}
651
+ class BackEnd extends Snail<CustomResponse, "records"> {}
652
652
 
653
- const res = await userApi.get<User>("1");
653
+ const res = await userApi.get<User>();
654
654
  // 自定义数据key
655
- // res.data => CustomResponse & { record : User}
655
+ // res.data => CustomResponse & { records : User}
656
656
  ```
657
657
 
658
- ### 非json数据的返回
659
- - 若后端返回的content-type不是json类型,send方法返回的将是`AxiosResponse`
660
- - 若后端返回的content-typejson类型,send方法返回的将是`AxiosResponse.data`
658
+ ### 非 json 数据的返回
659
+
660
+ - 若后端返回的 content-type 不是 json 类型,send 方法返回的将是`AxiosResponse`
661
+ - 若后端返回的 content-type 是 json 类型,send 方法返回的将是`AxiosResponse.data`
661
662
 
662
663
  ### 代码仓库
663
664
 
package/README_EN.md CHANGED
@@ -80,9 +80,9 @@ export const userApi = Service.createApi(UserApi);
80
80
  ```ts
81
81
  import { userApi } from "./user";
82
82
 
83
- const getUser = await userApi.get("1");
84
- const { send, onSuccess, onError, onHitCache, on } = getUser;
85
- const data = await send();
83
+ const { send:getUser, onSuccess, onError, onHitCache } = await userApi.get();
84
+
85
+ const data = await getUser("1");
86
86
  ```
87
87
 
88
88
  ## `SnailMethod` Instance
@@ -102,13 +102,8 @@ const data = await send();
102
102
  _Register cache hit event handler_
103
103
  - `onFinish`: Request completion callback
104
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_
105
+ - `registerStrategies` Register Strategies
106
+ _Register Strategies of this method instance_
112
107
 
113
108
  ### `SnailMethod` Properties
114
109
  - `response`: AxiosResponse - Raw response object
@@ -172,6 +167,13 @@ const data = await send();
172
167
  <td>Get</td>
173
168
  <td>Methods to enable caching</td>
174
169
  </tr>
170
+ <tr>
171
+ <td>serverStatusCodeRule</td>
172
+ <td><a href="#SnailServerStatusCodeRuleOptions">SnailServerStatusCodeRuleOptions</a></td>
173
+ <td>否</td>
174
+ <td>undefined</td>
175
+ <td>Server status code validation rules (triggers error when rule function returns false)</td>
176
+ </tr>
175
177
  <tr>
176
178
  <td>enableLog</td>
177
179
  <td>boolean</td>
@@ -303,8 +305,9 @@ class Test {
303
305
  // Register strategy before request
304
306
  const TestApi = Service.createApi(Test);
305
307
  const getSomething = TestApi.get();
306
- getSomething.registerStrategies(CustomStrategy);
307
308
  { send, registerStrategies } = getSomething;
309
+ registerStrategies(CustomStrategy);
310
+
308
311
  ```
309
312
 
310
313
  ### Response Strategy
@@ -385,6 +388,18 @@ export type VersioningOption =
385
388
  | VersioningCustomOption;
386
389
  ```
387
390
 
391
+ ### <a id="SnailServerStatusCodeRuleOptions">SnailServerStatusCodeRuleOptions</a> Type
392
+
393
+ ```typescript
394
+ export class SnailServerStatusCodeRuleOptions {
395
+ // Defines validation rules for server status codes
396
+ // Triggers error when rule function returns false
397
+ rule: (statusCode: number) => boolean;
398
+ // Specifies the key in response.data for status code (default: 'code')
399
+ key?: string;
400
+ }
401
+ ```
402
+
388
403
  ### Temporary Version Modifier @Version
389
404
  - Override version for specific methods
390
405
  ```typescript
@@ -533,10 +548,10 @@ class User {
533
548
  age: number;
534
549
  }
535
550
 
536
- const getUser = userApi.get<User>("1");
551
+ const getUser = userApi.get<User>();
537
552
  const { send } = getUser;
538
553
 
539
- const res = await send();
554
+ const res = await send("1");
540
555
 
541
556
  // Default data key:
542
557
  // res.data => CustomResponse & { data: User }
@@ -544,15 +559,15 @@ const res = await send();
544
559
 
545
560
  > API response format:
546
561
  ```typescript
547
- const getUser = userApi.get<User>("1");
562
+ const getUser = userApi.get<User>();
548
563
  const { send } = getUser;
549
- const res = await send();
564
+ const res = await send("1");
550
565
 
551
566
  // res.data => CustomResponse & { data: User }
552
567
 
553
- const getUser = userApi.get<Blob>("1");
568
+ const getUser = userApi.get<Blob>();
554
569
  const { send } = getUser;
555
- const res = await send();
570
+ const res = await send("1");
556
571
  // res => AxiosResponse<Blob>
557
572
  ```
558
573
 
@@ -565,8 +580,8 @@ const res = await send();
565
580
  })
566
581
  class BackEnd extends Snail<CustomResponse, "record"> {}
567
582
 
568
- const { send } = userApi.get<User>("1");
569
- const res = await send();
583
+ const { send } = userApi.get<User>();
584
+ const res = await send("1");
570
585
  // Custom data key:
571
586
  // res.data => CustomResponse & { record: User }
572
587
  ```
@@ -1,5 +1,5 @@
1
1
  import { AxiosResponse, AxiosRequestConfig } from "axios";
2
- import { EventHandler, Strategy, ResponseData, SendRequest, StandardResponseData, SnailMethodEventType } from "../typings";
2
+ import { Strategy, ResponseData, StandardResponseData, SnailSuccessListener, SnailErrorListener, SnailHitCacheListener, SnailFinishListener } from "../typings";
3
3
  import { SnailApi } from "./snailApi";
4
4
  /**
5
5
  * SnailMethod
@@ -14,29 +14,24 @@ export declare class SnailMethod<RT extends ResponseData = StandardResponseData>
14
14
  private Request;
15
15
  private Response;
16
16
  private Error;
17
- private eventMap;
18
- private onceWrapperMap;
17
+ private EventEmit;
19
18
  private propertyKey;
20
19
  private Url;
21
20
  private Path;
22
21
  private Method;
22
+ private Adapter;
23
23
  private Version?;
24
- private Args;
25
- constructor(apiInstance: SnailApi, target: Object, propertyKey: string | symbol, args?: []);
26
- send: SendRequest<RT>;
24
+ constructor(apiInstance: SnailApi, target: Object, propertyKey: string | symbol);
25
+ send: (...args: any) => Promise<unknown>;
27
26
  private init;
28
27
  private initUrl;
29
28
  private initVersion;
30
29
  private getExpireSources;
31
30
  private createRequest;
32
- onSuccess: (handler: EventHandler<RT>) => void;
33
- onError: (handler: EventHandler<RT>) => void;
34
- onHitCache: (handler: EventHandler<RT>) => void;
35
- onFinish: (handler: EventHandler<RT>) => void;
36
- on: (eventName: SnailMethodEventType, handler: EventHandler<RT>) => void;
37
- once: (eventName: SnailMethodEventType, handler: EventHandler<RT>) => void;
38
- emit: (eventName: SnailMethodEventType, ...args: any) => boolean;
39
- off: (eventName: SnailMethodEventType, handler: EventHandler<RT>) => void;
31
+ onSuccess: (listener: SnailSuccessListener<RT>) => void;
32
+ onError: <ErrorData = any>(listener: SnailErrorListener<RT, ErrorData>) => void;
33
+ onHitCache: (listener: SnailHitCacheListener<RT>) => void;
34
+ onFinish: (listener: SnailFinishListener<RT>) => void;
40
35
  private getCacheData;
41
36
  private setCacheData;
42
37
  get response(): AxiosResponse<RT, any>;
@@ -1,17 +1,17 @@
1
1
  import "reflect-metadata";
2
2
  import { AxiosInstance } from "axios";
3
- import { Strategy, ApiInstanceOptions, VersioningOption, CacheStorage, ApiProxy, ResponseData, StandardResponseData, CacheForType, SnailServerStatusCodeRuleOptions } from "../typings";
3
+ import { Strategy, ApiInstanceOptions, VersioningOption, CacheStorage, ApiProxy, StandardResponseWithoutData, SnailServerStatusCodeRuleOptions, ResponseJsonData } from "../typings";
4
4
  import { SnailApi } from "./snailApi";
5
5
  import { SnailSse } from "./snailSse";
6
6
  export declare const CacheStorageMap: Map<string, CacheStorage>;
7
7
  export declare const CacheTtlMap: Map<string, number>;
8
- export declare const CacheForMap: Map<string, CacheForType>;
8
+ export declare const CacheForMap: Map<string, string[]>;
9
9
  export declare const ExpireSourceMap: Map<string, Set<string>>;
10
10
  export declare const AxiosInstanceMap: Map<string, AxiosInstance>;
11
11
  export declare const StrategyMap: Map<string, (new () => Strategy)[]>;
12
12
  export declare const VersioningMap: Map<string, VersioningOption>;
13
13
  export declare const ServerStatusCodeRuleMap: Map<string, SnailServerStatusCodeRuleOptions>;
14
- export declare class SnailServer<RT extends ResponseData = Omit<StandardResponseData, "data">, DK extends string = "data"> {
14
+ export declare class SnailServer<RT extends StandardResponseWithoutData | ResponseJsonData = StandardResponseWithoutData, DK extends string = "data"> {
15
15
  private Name;
16
16
  private BaseURL;
17
17
  private Version;
@@ -23,7 +23,7 @@ export declare class SnailServer<RT extends ResponseData = Omit<StandardResponse
23
23
  private initStrategy;
24
24
  private initVersioning;
25
25
  registerStrategies: (...strategys: Array<new () => Strategy>) => void;
26
- createApi<T extends SnailApi>(constructor: new (options: ApiInstanceOptions) => T): ApiProxy<T, RT, DK>;
26
+ createApi<TApiClass extends SnailApi>(constructor: new (options: ApiInstanceOptions) => TApiClass): ApiProxy<TApiClass, RT, DK>;
27
27
  private initCacheManage;
28
28
  private initExpireSource;
29
29
  private initAxios;
@@ -1,40 +1,4 @@
1
1
  import "reflect-metadata";
2
2
  import { ApiOptions } from "../typings";
3
- export declare const METHOD_KEY: unique symbol;
4
3
  export declare const API_CONFIG_KEY: unique symbol;
5
4
  export declare const Api: (url?: string, config?: ApiOptions) => ClassDecorator;
6
- /**
7
- * 定义装饰的方法为Get请求
8
- * @param path 字符型,请求端点,默认为空
9
- */
10
- export declare const Get: (path?: string, name?: string) => (target: any, propertyKey: string | symbol) => void;
11
- /**
12
- * 定义装饰的方法为Post请求
13
- * @param path 字符型,请求端点,默认为空
14
- */
15
- export declare const Post: (path?: string, name?: string) => (target: any, propertyKey: string | symbol) => void;
16
- /**
17
- * 定义装饰的方法为Put请求
18
- * @param path 字符型,请求端点,默认为空
19
- */
20
- export declare const Put: (path?: string, name?: string) => (target: any, propertyKey: string | symbol) => void;
21
- /**
22
- * 定义装饰的方法为Delete请求
23
- * @param path 字符型,请求端点,默认为空
24
- */
25
- export declare const Delete: (path?: string, name?: string) => (target: any, propertyKey: string | symbol) => void;
26
- /**
27
- * 定义装饰的方法为Patch请求
28
- * @param path 字符型,请求端点,默认为空
29
- */
30
- export declare const Patch: (path?: string, name?: string) => (target: any, propertyKey: string | symbol) => void;
31
- /**
32
- * 定义装饰的方法为Options请求
33
- * @param path 字符型,请求端点,默认为空
34
- */
35
- export declare const Options: (path?: string, name?: string) => (target: any, propertyKey: string | symbol) => void;
36
- /**
37
- * 定义装饰的方法为Head请求
38
- * @param path 字符型,请求端点,默认为空
39
- */
40
- export declare const Head: (path?: string, name?: string) => (target: any, propertyKey: string | symbol) => void;
@@ -0,0 +1,38 @@
1
+ import "reflect-metadata";
2
+ import { MethodSendOptions } from "../typings";
3
+ export declare const METHOD_KEY: unique symbol;
4
+ /**
5
+ * 定义装饰的方法为Get请求
6
+ * @param path 字符型,请求端点,默认为空
7
+ */
8
+ export declare const Get: (path?: string, options?: MethodSendOptions) => (target: any, propertyKey: string | symbol) => void;
9
+ /**
10
+ * 定义装饰的方法为Post请求
11
+ * @param path 字符型,请求端点,默认为空
12
+ */
13
+ export declare const Post: (path?: string, options?: MethodSendOptions) => (target: any, propertyKey: string | symbol) => void;
14
+ /**
15
+ * 定义装饰的方法为Put请求
16
+ * @param path 字符型,请求端点,默认为空
17
+ */
18
+ export declare const Put: (path?: string, options?: MethodSendOptions) => (target: any, propertyKey: string | symbol) => void;
19
+ /**
20
+ * 定义装饰的方法为Delete请求
21
+ * @param path 字符型,请求端点,默认为空
22
+ */
23
+ export declare const Delete: (path?: string, options?: MethodSendOptions) => (target: any, propertyKey: string | symbol) => void;
24
+ /**
25
+ * 定义装饰的方法为Patch请求
26
+ * @param path 字符型,请求端点,默认为空
27
+ */
28
+ export declare const Patch: (path?: string, options?: MethodSendOptions) => (target: any, propertyKey: string | symbol) => void;
29
+ /**
30
+ * 定义装饰的方法为Options请求
31
+ * @param path 字符型,请求端点,默认为空
32
+ */
33
+ export declare const Options: (path?: string, options?: MethodSendOptions) => (target: any, propertyKey: string | symbol) => void;
34
+ /**
35
+ * 定义装饰的方法为Head请求
36
+ * @param path 字符型,请求端点,默认为空
37
+ */
38
+ export declare const Head: (path?: string, options?: MethodSendOptions) => (target: any, propertyKey: string | symbol) => void;
@@ -0,0 +1 @@
1
+ export * from "./snail.event";
@@ -0,0 +1,10 @@
1
+ import { SnailEventListener } from "../typings";
2
+ export declare class SnailEvent<DT = any> {
3
+ private eventMap;
4
+ private onceWrapperMap;
5
+ constructor();
6
+ on: <ErrorData = any>(eventName: string, listener: SnailEventListener<DT, ErrorData>) => void;
7
+ off: (eventName: string, listener: SnailEventListener<DT>) => void;
8
+ once: (eventName: string, listener: SnailEventListener<DT>) => void;
9
+ emit: (eventName: string, ...args: any) => boolean;
10
+ }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from "./core";
2
2
  export { Server } from "./decorators/server";
3
- export { Api, Get, Put, Post, Patch, Options, Head, Delete, } from "./decorators/api";
3
+ export { Api } from "./decorators/api";
4
+ export { Get, Put, Post, Patch, Options, Head, Delete, } from "./decorators/method";
4
5
  export { NoCache, HitSource } from "./decorators/cache";
5
6
  export { Params, Data, Query } from "./decorators/args";
6
7
  export { UseStrategy } from "./decorators/strategy";