@celljs/http 4.2.0 → 4.4.0

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 (55) hide show
  1. package/README.md +66 -1
  2. package/cell.schema.json +17 -0
  3. package/cell.yml +4 -5
  4. package/esm/common/client/client-protocol.d.ts +51 -5
  5. package/esm/common/client/client-protocol.js.map +1 -1
  6. package/esm/common/client/default-rest-operations.d.ts +30 -0
  7. package/esm/common/client/default-rest-operations.js +224 -0
  8. package/esm/common/client/default-rest-operations.js.map +1 -0
  9. package/esm/common/client/http-client-error.d.ts +25 -0
  10. package/esm/common/client/http-client-error.js +22 -0
  11. package/esm/common/client/http-client-error.js.map +1 -0
  12. package/esm/common/client/index.d.ts +3 -0
  13. package/esm/common/client/index.js +3 -0
  14. package/esm/common/client/index.js.map +1 -1
  15. package/esm/common/client/interceptor-manager.d.ts +14 -0
  16. package/esm/common/client/interceptor-manager.js +27 -0
  17. package/esm/common/client/interceptor-manager.js.map +1 -0
  18. package/esm/common/client/rest-operations-factory.d.ts +2 -3
  19. package/esm/common/client/rest-operations-factory.js +4 -4
  20. package/esm/common/client/rest-operations-factory.js.map +1 -1
  21. package/lib/common/client/client-protocol.d.ts +51 -5
  22. package/lib/common/client/client-protocol.d.ts.map +1 -1
  23. package/lib/common/client/client-protocol.js.map +1 -1
  24. package/lib/common/client/default-rest-operations.d.ts +31 -0
  25. package/lib/common/client/default-rest-operations.d.ts.map +1 -0
  26. package/lib/common/client/default-rest-operations.js +228 -0
  27. package/lib/common/client/default-rest-operations.js.map +1 -0
  28. package/lib/common/client/default-rest-operations.spec.d.ts +2 -0
  29. package/lib/common/client/default-rest-operations.spec.d.ts.map +1 -0
  30. package/lib/common/client/default-rest-operations.spec.js +168 -0
  31. package/lib/common/client/default-rest-operations.spec.js.map +1 -0
  32. package/lib/common/client/http-client-error.d.ts +26 -0
  33. package/lib/common/client/http-client-error.d.ts.map +1 -0
  34. package/lib/common/client/http-client-error.js +26 -0
  35. package/lib/common/client/http-client-error.js.map +1 -0
  36. package/lib/common/client/index.d.ts +3 -0
  37. package/lib/common/client/index.d.ts.map +1 -1
  38. package/lib/common/client/index.js +3 -0
  39. package/lib/common/client/index.js.map +1 -1
  40. package/lib/common/client/interceptor-manager.d.ts +15 -0
  41. package/lib/common/client/interceptor-manager.d.ts.map +1 -0
  42. package/lib/common/client/interceptor-manager.js +31 -0
  43. package/lib/common/client/interceptor-manager.js.map +1 -0
  44. package/lib/common/client/rest-operations-factory.d.ts +2 -3
  45. package/lib/common/client/rest-operations-factory.d.ts.map +1 -1
  46. package/lib/common/client/rest-operations-factory.js +4 -7
  47. package/lib/common/client/rest-operations-factory.js.map +1 -1
  48. package/package.json +4 -4
  49. package/src/common/client/client-protocol.ts +53 -5
  50. package/src/common/client/default-rest-operations.spec.ts +190 -0
  51. package/src/common/client/default-rest-operations.ts +237 -0
  52. package/src/common/client/http-client-error.ts +31 -0
  53. package/src/common/client/index.ts +3 -0
  54. package/src/common/client/interceptor-manager.ts +33 -0
  55. package/src/common/client/rest-operations-factory.ts +5 -5
@@ -1,3 +1,6 @@
1
1
  export * from './client-protocol';
2
+ export * from './interceptor-manager';
3
+ export * from './http-client-error';
4
+ export * from './default-rest-operations';
2
5
  export * from './rest-operations-factory';
3
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/common/client/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,2BAA2B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/common/client/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,2BAA2B,CAAC"}
@@ -15,5 +15,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./client-protocol"), exports);
18
+ __exportStar(require("./interceptor-manager"), exports);
19
+ __exportStar(require("./http-client-error"), exports);
20
+ __exportStar(require("./default-rest-operations"), exports);
18
21
  __exportStar(require("./rest-operations-factory"), exports);
19
22
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/client/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,oDAAkC;AAClC,4DAA0C"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/client/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,oDAAkC;AAClC,wDAAsC;AACtC,sDAAoC;AACpC,4DAA0C;AAC1C,4DAA0C"}
@@ -0,0 +1,15 @@
1
+ export interface Interceptor<V> {
2
+ fulfilled?: (value: V) => V | Promise<V>;
3
+ rejected?: (error: any) => any;
4
+ }
5
+ /** Interceptors run in the order they were added, each one on the result of the previous one. */
6
+ export declare class InterceptorManager<V> {
7
+ protected readonly handlers: Map<number, Interceptor<V>>;
8
+ protected nextId: number;
9
+ /** Returns the id to `eject` the interceptor with. */
10
+ use(fulfilled?: Interceptor<V>['fulfilled'], rejected?: Interceptor<V>['rejected']): number;
11
+ eject(id: number): void;
12
+ clear(): void;
13
+ apply(value: Promise<V>): Promise<V>;
14
+ }
15
+ //# sourceMappingURL=interceptor-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interceptor-manager.d.ts","sourceRoot":"","sources":["../../../src/common/client/interceptor-manager.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW,CAAC,CAAC;IAC1B,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACzC,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,GAAG,CAAC;CAClC;AAED,iGAAiG;AACjG,qBAAa,kBAAkB,CAAC,CAAC;IAC7B,SAAS,CAAC,QAAQ,CAAC,QAAQ,8BAAqC;IAChE,SAAS,CAAC,MAAM,SAAK;IAErB,sDAAsD;IACtD,GAAG,CAAC,SAAS,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,QAAQ,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,MAAM,CAI1F;IAED,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAEtB;IAED,KAAK,IAAI,IAAI,CAEZ;IAED,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAMnC;CACJ"}
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InterceptorManager = void 0;
4
+ /** Interceptors run in the order they were added, each one on the result of the previous one. */
5
+ class InterceptorManager {
6
+ constructor() {
7
+ this.handlers = new Map();
8
+ this.nextId = 0;
9
+ }
10
+ /** Returns the id to `eject` the interceptor with. */
11
+ use(fulfilled, rejected) {
12
+ const id = this.nextId++;
13
+ this.handlers.set(id, { fulfilled, rejected });
14
+ return id;
15
+ }
16
+ eject(id) {
17
+ this.handlers.delete(id);
18
+ }
19
+ clear() {
20
+ this.handlers.clear();
21
+ }
22
+ apply(value) {
23
+ let result = value;
24
+ for (const { fulfilled, rejected } of this.handlers.values()) {
25
+ result = result.then(fulfilled, rejected);
26
+ }
27
+ return result;
28
+ }
29
+ }
30
+ exports.InterceptorManager = InterceptorManager;
31
+ //# sourceMappingURL=interceptor-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interceptor-manager.js","sourceRoot":"","sources":["../../../src/common/client/interceptor-manager.ts"],"names":[],"mappings":";;;AAKA,iGAAiG;AACjG;IAAA;QACuB,aAAQ,GAAG,IAAI,GAAG,EAA0B,CAAC;QACtD,WAAM,GAAG,CAAC,CAAC;IAwBzB,CAAC;IAtBG,sDAAsD;IACtD,GAAG,CAAC,SAAuC,EAAE,QAAqC;QAC9E,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QACzB,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC/C,OAAO,EAAE,CAAC;IACd,CAAC;IAED,KAAK,CAAC,EAAU;QACZ,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAC7B,CAAC;IAED,KAAK;QACD,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,KAAiB;QACnB,IAAI,MAAM,GAAG,KAAK,CAAC;QACnB,KAAK,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;YAC3D,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ"}
@@ -1,7 +1,6 @@
1
- import { RestOperationsFactory, RestOperations } from './client-protocol';
2
- import { AxiosRequestConfig } from 'axios';
1
+ import { RequestConfig, RestOperations, RestOperationsFactory } from './client-protocol';
3
2
  export declare class DefaultRestOperationsFactory implements RestOperationsFactory {
4
- protected readonly clientConfig: AxiosRequestConfig;
3
+ protected readonly clientConfig?: RequestConfig;
5
4
  create(): RestOperations;
6
5
  }
7
6
  //# sourceMappingURL=rest-operations-factory.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"rest-operations-factory.d.ts","sourceRoot":"","sources":["../../../src/common/client/rest-operations-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAc,EAAE,kBAAkB,EAAE,MAAM,OAAO,CAAC;AAGlD,qBACa,4BAA6B,YAAW,qBAAqB;IAGtE,SAAS,CAAC,QAAQ,CAAC,YAAY,EAAE,kBAAkB,CAAC;IAEpD,MAAM,IAAI,cAAc,CAEvB;CAEJ"}
1
+ {"version":3,"file":"rest-operations-factory.d.ts","sourceRoot":"","sources":["../../../src/common/client/rest-operations-factory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAGzF,qBACa,4BAA6B,YAAW,qBAAqB;IAGtE,SAAS,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,aAAa,CAAC;IAEhD,MAAM,IAAI,cAAc,CAEvB;CAEJ"}
@@ -8,22 +8,19 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
11
  Object.defineProperty(exports, "__esModule", { value: true });
15
12
  exports.DefaultRestOperationsFactory = void 0;
16
- const client_protocol_1 = require("./client-protocol");
17
- const axios_1 = __importDefault(require("axios"));
18
13
  const core_1 = require("@celljs/core");
14
+ const client_protocol_1 = require("./client-protocol");
15
+ const default_rest_operations_1 = require("./default-rest-operations");
19
16
  let DefaultRestOperationsFactory = class DefaultRestOperationsFactory {
20
17
  create() {
21
- return axios_1.default.create(this.clientConfig);
18
+ return new default_rest_operations_1.DefaultRestOperations(this.clientConfig);
22
19
  }
23
20
  };
24
21
  exports.DefaultRestOperationsFactory = DefaultRestOperationsFactory;
25
22
  __decorate([
26
- (0, core_1.Value)('cell.client.config'),
23
+ (0, core_1.Value)('http.client'),
27
24
  __metadata("design:type", Object)
28
25
  ], DefaultRestOperationsFactory.prototype, "clientConfig", void 0);
29
26
  exports.DefaultRestOperationsFactory = DefaultRestOperationsFactory = __decorate([
@@ -1 +1 @@
1
- {"version":3,"file":"rest-operations-factory.js","sourceRoot":"","sources":["../../../src/common/client/rest-operations-factory.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,uDAA0E;AAC1E,kDAAkD;AAClD,uCAAgD;AAGzC,IAAM,4BAA4B,GAAlC,MAAM,4BAA4B;IAKrC,MAAM;QACF,OAAO,eAAK,CAAC,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC3C,CAAC;CAEJ,CAAA;;AANsB;IADlB,IAAA,YAAK,EAAC,oBAAoB,CAAC;;kEACwB;uCAH3C,4BAA4B;IADxC,IAAA,gBAAS,EAAC,uCAAqB,CAAC;GACpB,4BAA4B,CASxC"}
1
+ {"version":3,"file":"rest-operations-factory.js","sourceRoot":"","sources":["../../../src/common/client/rest-operations-factory.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,uCAAgD;AAChD,uDAAyF;AACzF,uEAAkE;AAG3D,IAAM,4BAA4B,GAAlC,MAAM,4BAA4B;IAKrC,MAAM;QACF,OAAO,IAAI,+CAAqB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACxD,CAAC;CAEJ,CAAA;;AANsB;IADlB,IAAA,YAAK,EAAC,aAAa,CAAC;;kEAC2B;uCAHvC,4BAA4B;IADxC,IAAA,gBAAS,EAAC,uCAAqB,CAAC;GACpB,4BAA4B,CASxC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/http",
3
- "version": "4.2.0",
3
+ "version": "4.4.0",
4
4
  "description": "",
5
5
  "keywords": [
6
6
  "cell-component"
@@ -23,7 +23,8 @@
23
23
  "lib",
24
24
  "esm",
25
25
  "src",
26
- "cell.yml"
26
+ "cell.yml",
27
+ "cell.schema.json"
27
28
  ],
28
29
  "scripts": {
29
30
  "build": "tsc -b && bun ../../scripts/build-esm.ts",
@@ -32,8 +33,7 @@
32
33
  "watch": "tsc -b -w --preserveWatchOutput"
33
34
  },
34
35
  "dependencies": {
35
- "@celljs/core": "4.2.0",
36
- "axios": "^0.35.0"
36
+ "@celljs/core": "4.4.0"
37
37
  },
38
38
  "publishConfig": {
39
39
  "access": "public"
@@ -1,10 +1,58 @@
1
- import { AxiosInstance, AxiosResponseHeaders } from 'axios';
1
+ import type { InterceptorManager } from './interceptor-manager';
2
2
 
3
3
  export const RestOperations = Symbol('RestOperations');
4
4
  export const RestOperationsFactory = Symbol('RestOperationsFactory');
5
5
 
6
- export interface RestOperations extends AxiosInstance {
6
+ /** How the body of a response is read; by default it is parsed as JSON when it is JSON and kept as text otherwise. */
7
+ export type ResponseType = 'json' | 'text' | 'arraybuffer' | 'blob' | 'stream';
7
8
 
9
+ export interface RequestConfig {
10
+ url?: string;
11
+ method?: string;
12
+ /** Prefixed to `url` unless `url` is absolute. */
13
+ baseURL?: string;
14
+ headers?: Record<string, string | number | boolean | undefined>;
15
+ /** Appended to the query string; an array repeats the key, `undefined` and `null` are left out. */
16
+ params?: Record<string, unknown> | URLSearchParams;
17
+ /** Sent as is when it is a string, `URLSearchParams`, `FormData`, `Blob`, binary data or a stream, as JSON otherwise. */
18
+ data?: unknown;
19
+ /** Milliseconds before the request is aborted with `CELL_HTTP_TIMEOUT`; no limit by default. */
20
+ timeout?: number;
21
+ /** Sends cookies cross-origin in the browser (`credentials: 'include'`). */
22
+ withCredentials?: boolean;
23
+ responseType?: ResponseType;
24
+ signal?: AbortSignal;
25
+ /** Which statuses resolve; the others reject with `CELL_HTTP_BAD_STATUS`. `null` resolves every status. Default: 2xx. */
26
+ validateStatus?: ((status: number) => boolean) | null;
27
+ }
28
+
29
+ export interface RestResponse<T = any> {
30
+ status: number;
31
+ statusText: string;
32
+ /** Lower-case header names. */
33
+ headers: Record<string, string>;
34
+ data: T;
35
+ config: RequestConfig;
36
+ }
37
+
38
+ /**
39
+ * An HTTP client on `fetch` with the axios-style API: `get`, `post`, ... resolve to a `RestResponse`
40
+ * and reject with an `HttpClientError` when the status is not 2xx.
41
+ */
42
+ export interface RestOperations {
43
+ readonly defaults: RequestConfig;
44
+ readonly interceptors: {
45
+ request: InterceptorManager<RequestConfig>;
46
+ response: InterceptorManager<RestResponse>;
47
+ };
48
+ request<T = any>(config: RequestConfig): Promise<RestResponse<T>>;
49
+ get<T = any>(url: string, config?: RequestConfig): Promise<RestResponse<T>>;
50
+ delete<T = any>(url: string, config?: RequestConfig): Promise<RestResponse<T>>;
51
+ head<T = any>(url: string, config?: RequestConfig): Promise<RestResponse<T>>;
52
+ options<T = any>(url: string, config?: RequestConfig): Promise<RestResponse<T>>;
53
+ post<T = any>(url: string, data?: unknown, config?: RequestConfig): Promise<RestResponse<T>>;
54
+ put<T = any>(url: string, data?: unknown, config?: RequestConfig): Promise<RestResponse<T>>;
55
+ patch<T = any>(url: string, data?: unknown, config?: RequestConfig): Promise<RestResponse<T>>;
8
56
  }
9
57
 
10
58
  export interface RestOperationsFactory {
@@ -13,12 +61,12 @@ export interface RestOperationsFactory {
13
61
 
14
62
  export interface ResponseEntity<T> {
15
63
  status: number;
16
- headers: AxiosResponseHeaders;
64
+ headers: Record<string, string>;
17
65
  body: T;
18
66
  }
19
67
 
20
68
  export class ResponseEntityUtil {
21
- static ok<T>(body: T, headers?: AxiosResponseHeaders): ResponseEntity<T> {
69
+ static ok<T>(body: T, headers?: Record<string, string>): ResponseEntity<T> {
22
70
  return {
23
71
  status: 200,
24
72
  headers: headers || {},
@@ -26,7 +74,7 @@ export class ResponseEntityUtil {
26
74
  };
27
75
  }
28
76
 
29
- static created<T>(body: T, headers?: AxiosResponseHeaders): ResponseEntity<T> {
77
+ static created<T>(body: T, headers?: Record<string, string>): ResponseEntity<T> {
30
78
  return {
31
79
  status: 201,
32
80
  headers: headers || {},
@@ -0,0 +1,190 @@
1
+ import { describe, it, beforeAll, afterAll, expect } from 'bun:test';
2
+ import { createServer, IncomingMessage, Server, ServerResponse } from 'node:http';
3
+ import { AddressInfo } from 'node:net';
4
+ import { DefaultRestOperations } from './default-rest-operations';
5
+ import { HttpClientError } from './http-client-error';
6
+
7
+ interface Seen {
8
+ method?: string;
9
+ url?: string;
10
+ headers: IncomingMessage['headers'];
11
+ body: string;
12
+ }
13
+
14
+ let server: Server;
15
+ let base: string;
16
+ let seen: Seen;
17
+
18
+ /** Echoes what it received, or answers what the path asks for. */
19
+ function handle(req: IncomingMessage, res: ServerResponse, body: string): void {
20
+ seen = { method: req.method, url: req.url, headers: req.headers, body };
21
+ const path = req.url!.split('?')[0];
22
+ if (path === '/status/404') {
23
+ res.writeHead(404, { 'content-type': 'application/json' }).end(JSON.stringify({ message: 'missing' }));
24
+ } else if (path === '/text') {
25
+ res.writeHead(200, { 'content-type': 'text/plain' }).end('Welcome to Cell');
26
+ } else if (path === '/empty') {
27
+ res.writeHead(204).end();
28
+ } else if (path === '/slow') {
29
+ setTimeout(() => res.end('late'), 500);
30
+ } else if (path === '/cookies') {
31
+ res.setHeader('set-cookie', [ 'a=1', 'b=2' ]);
32
+ res.end();
33
+ } else {
34
+ res.writeHead(200, { 'content-type': 'application/json', 'X-Custom': 'yes' }).end(JSON.stringify({ ok: true }));
35
+ }
36
+ }
37
+
38
+ beforeAll(async () => {
39
+ server = createServer((req, res) => {
40
+ let body = '';
41
+ req.on('data', chunk => body += chunk);
42
+ req.on('end', () => handle(req, res, body));
43
+ });
44
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
45
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
46
+ });
47
+
48
+ afterAll(() => {
49
+ server.closeAllConnections();
50
+ server.close();
51
+ });
52
+
53
+ async function failure(promise: Promise<unknown>): Promise<HttpClientError> {
54
+ try {
55
+ await promise;
56
+ } catch (error) {
57
+ expect(error).toBeInstanceOf(HttpClientError);
58
+ return error as HttpClientError;
59
+ }
60
+ throw new Error('the request did not fail');
61
+ }
62
+
63
+ describe('DefaultRestOperations', () => {
64
+
65
+ it('joins baseURL and url, appends params, parses a JSON answer and lower-cases its headers', async () => {
66
+ const rest = new DefaultRestOperations({ baseURL: base + '/v1/' });
67
+ const response = await rest.get('/items', { params: { q: 'a b', tag: [ 'x', 'y' ], skip: undefined, at: new Date(0) } });
68
+ expect(response.status).toBe(200);
69
+ expect(response.data).toEqual({ ok: true });
70
+ expect(response.headers['x-custom']).toBe('yes');
71
+ expect(seen.url).toBe('/v1/items?q=a+b&tag=x&tag=y&at=1970-01-01T00%3A00%3A00.000Z');
72
+ });
73
+
74
+ it('keeps an absolute url and appends params to an existing query string', async () => {
75
+ const rest = new DefaultRestOperations({ baseURL: 'http://unused.invalid' });
76
+ await rest.get(base + '/items?a=1', { params: { b: 2 } });
77
+ expect(seen.url).toBe('/items?a=1&b=2');
78
+ });
79
+
80
+ it('merges the default headers with the request headers, case-insensitively', async () => {
81
+ const rest = new DefaultRestOperations({ headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-Team': 'a' } });
82
+ await rest.get(base, { headers: { 'x-team': 'b', 'X-Skip': undefined } });
83
+ expect(seen.headers['x-requested-with']).toBe('XMLHttpRequest');
84
+ expect(seen.headers['x-team']).toBe('b');
85
+ expect(seen.headers['x-skip']).toBeUndefined();
86
+ });
87
+
88
+ it('sends an object as JSON and a string as is', async () => {
89
+ const rest = new DefaultRestOperations();
90
+ await rest.post(base, { name: 'Tom' });
91
+ expect(seen.method).toBe('POST');
92
+ expect(seen.headers['content-type']).toBe('application/json');
93
+ expect(JSON.parse(seen.body)).toEqual({ name: 'Tom' });
94
+
95
+ await rest.put(base, 'grant_type=refresh_token', { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
96
+ expect(seen.method).toBe('PUT');
97
+ expect(seen.headers['content-type']).toBe('application/x-www-form-urlencoded');
98
+ expect(seen.body).toBe('grant_type=refresh_token');
99
+
100
+ await rest.patch(base, new URLSearchParams({ a: '1' }));
101
+ expect(seen.headers['content-type']).toStartWith('application/x-www-form-urlencoded');
102
+ expect(seen.body).toBe('a=1');
103
+ });
104
+
105
+ it('does not send a body with GET', async () => {
106
+ await new DefaultRestOperations().request({ url: base, data: { a: 1 } });
107
+ expect(seen.method).toBe('GET');
108
+ expect(seen.body).toBe('');
109
+ });
110
+
111
+ it('keeps an answer that is not JSON as text and an empty one as an empty string', async () => {
112
+ const rest = new DefaultRestOperations();
113
+ expect((await rest.get(base + '/text')).data).toBe('Welcome to Cell');
114
+ const empty = await rest.delete(base + '/empty');
115
+ expect(empty.status).toBe(204);
116
+ expect(empty.data).toBe('');
117
+ });
118
+
119
+ it('reads the body as the responseType says', async () => {
120
+ const rest = new DefaultRestOperations();
121
+ expect((await rest.get(base, { responseType: 'text' })).data).toBe('{"ok":true}');
122
+ const buffer = (await rest.get(base + '/text', { responseType: 'arraybuffer' })).data as ArrayBuffer;
123
+ expect(new TextDecoder().decode(buffer)).toBe('Welcome to Cell');
124
+ });
125
+
126
+ it('joins repeated answer headers', async () => {
127
+ const response = await new DefaultRestOperations().get(base + '/cookies');
128
+ expect(response.headers['set-cookie']).toBe('a=1, b=2');
129
+ });
130
+
131
+ it('rejects a status that is not 2xx with CELL_HTTP_BAD_STATUS and the answer', async () => {
132
+ const error = await failure(new DefaultRestOperations().get(base + '/status/404'));
133
+ expect(error.code).toBe('CELL_HTTP_BAD_STATUS');
134
+ expect(error.response!.status).toBe(404);
135
+ expect(error.response!.data).toEqual({ message: 'missing' });
136
+ expect(error.message).toContain('GET ' + base + '/status/404 answered 404');
137
+ expect(HttpClientError.is(error, 'CELL_HTTP_BAD_STATUS')).toBe(true);
138
+ });
139
+
140
+ it('resolves every status when validateStatus is null', async () => {
141
+ const response = await new DefaultRestOperations({ validateStatus: null }).get(base + '/status/404');
142
+ expect(response.status).toBe(404);
143
+ });
144
+
145
+ it('rejects with CELL_HTTP_TIMEOUT after timeout ms', async () => {
146
+ const error = await failure(new DefaultRestOperations({ timeout: 50 }).get(base + '/slow'));
147
+ expect(error.code).toBe('CELL_HTTP_TIMEOUT');
148
+ });
149
+
150
+ it('rejects with CELL_HTTP_ABORTED when the signal is aborted', async () => {
151
+ const controller = new AbortController();
152
+ const pending = new DefaultRestOperations({ timeout: 5000 }).get(base + '/slow', { signal: controller.signal });
153
+ setTimeout(() => controller.abort(), 20);
154
+ expect((await failure(pending)).code).toBe('CELL_HTTP_ABORTED');
155
+ controller.abort();
156
+ });
157
+
158
+ it('rejects with CELL_HTTP_NETWORK when the server cannot be reached', async () => {
159
+ const closed = createServer();
160
+ await new Promise<void>(resolve => closed.listen(0, '127.0.0.1', resolve));
161
+ const port = (closed.address() as AddressInfo).port;
162
+ await new Promise<void>(resolve => closed.close(() => resolve()));
163
+ const error = await failure(new DefaultRestOperations().get(`http://127.0.0.1:${port}/`));
164
+ expect(error.code).toBe('CELL_HTTP_NETWORK');
165
+ expect(error.cause).toBeDefined();
166
+ });
167
+
168
+ it('runs request interceptors in order before sending and response interceptors after', async () => {
169
+ const rest = new DefaultRestOperations();
170
+ rest.interceptors.request.use(config => ({ ...config, headers: { ...config.headers, 'X-Order': '1' } }));
171
+ rest.interceptors.request.use(config => ({ ...config, headers: { ...config.headers, 'X-Order': String(config.headers!['X-Order']) + '2' } }));
172
+ const id = rest.interceptors.response.use(response => ({ ...response, data: { wrapped: response.data } }));
173
+ expect((await rest.get(base)).data).toEqual({ wrapped: { ok: true } });
174
+ expect(seen.headers['x-order']).toBe('12');
175
+
176
+ rest.interceptors.response.eject(id);
177
+ expect((await rest.get(base)).data).toEqual({ ok: true });
178
+ });
179
+
180
+ it('lets a response interceptor turn a failure into a value', async () => {
181
+ const rest = new DefaultRestOperations();
182
+ rest.interceptors.response.use(undefined, error => {
183
+ if (HttpClientError.is(error) && error.response?.status === 404) {
184
+ return { ...error.response, data: 'handled' };
185
+ }
186
+ return Promise.reject(error);
187
+ });
188
+ expect((await rest.get(base + '/status/404')).data).toBe('handled');
189
+ });
190
+ });