@nmtjs/http-client 0.0.1

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/LICENSE.md ADDED
@@ -0,0 +1,7 @@
1
+ Copyright (c) 2024 Denis Ilchyshyn
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ ## HTTP transport for [Neemata](https://github.com/neematajs/neemata)
package/dist/index.js ADDED
@@ -0,0 +1,82 @@
1
+ import { ClientTransport } from '@nmtjs/client';
2
+ import { ErrorCode, TransportType } from '@nmtjs/common';
3
+ export class HttpClient extends ClientTransport {
4
+ options;
5
+ type;
6
+ attempts;
7
+ constructor(options){
8
+ super();
9
+ this.options = options;
10
+ this.type = TransportType.HTTP;
11
+ this.attempts = 0;
12
+ }
13
+ async healthCheck() {
14
+ while(true){
15
+ try {
16
+ const signal = AbortSignal.timeout(10000);
17
+ const url = this.getURL('healthy');
18
+ const { ok } = await fetch(url, {
19
+ signal
20
+ });
21
+ if (ok) break;
22
+ } catch (e) {}
23
+ this.attempts++;
24
+ const seconds = Math.min(this.attempts, 15);
25
+ await new Promise((r)=>setTimeout(r, seconds * 1000));
26
+ }
27
+ }
28
+ async connect() {}
29
+ async disconnect() {}
30
+ async rpc(params) {
31
+ const { service, procedure, payload, signal } = params;
32
+ const url = this.getURL(`api/${service}/${procedure}`);
33
+ const body = this.client.format.encode(payload);
34
+ const response = await fetch(url, {
35
+ method: 'POST',
36
+ body,
37
+ signal,
38
+ keepalive: true,
39
+ credentials: 'include',
40
+ cache: 'no-cache',
41
+ headers: {
42
+ 'Content-Type': this.client.format.contentType,
43
+ Accept: this.client.format.contentType,
44
+ ...this.client.auth ? {
45
+ Authorization: this.client.auth
46
+ } : {}
47
+ }
48
+ });
49
+ if (!response.ok) {
50
+ return {
51
+ success: false,
52
+ error: {
53
+ code: ErrorCode.InternalServerError,
54
+ data: {
55
+ status: response.status,
56
+ statusText: response.statusText
57
+ },
58
+ message: await response.text()
59
+ }
60
+ };
61
+ } else {
62
+ const buf = await response.arrayBuffer();
63
+ const { error, response: rpcResponse } = this.client.format.decode(buf);
64
+ if (error) {
65
+ return {
66
+ success: false,
67
+ error
68
+ };
69
+ } else {
70
+ return {
71
+ success: true,
72
+ value: rpcResponse
73
+ };
74
+ }
75
+ }
76
+ }
77
+ getURL(path = '', params = '') {
78
+ const url = new URL(path, this.options.origin);
79
+ url.search = params;
80
+ return url;
81
+ }
82
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../index.ts"],"sourcesContent":["import {\n ClientTransport,\n type ClientTransportRpcCall,\n type ClientTransportRpcResult,\n} from '@nmtjs/client'\nimport { ErrorCode, TransportType } from '@nmtjs/common'\n\nexport type ClientOptions = {\n /**\n * The origin of the server\n * @example 'http://localhost:3000'\n */\n origin: string\n debug?: boolean\n}\n\nexport type HttpRpcOptions = {\n timeout?: number\n headers?: Record<string, string>\n signal?: AbortSignal\n}\n\nexport class HttpClient extends ClientTransport {\n type = TransportType.HTTP\n private attempts = 0\n\n constructor(private readonly options: ClientOptions) {\n super()\n }\n\n async healthCheck() {\n while (true) {\n try {\n const signal = AbortSignal.timeout(10000)\n const url = this.getURL('healthy')\n const { ok } = await fetch(url, { signal })\n if (ok) break\n } catch (e) {}\n this.attempts++\n const seconds = Math.min(this.attempts, 15)\n await new Promise((r) => setTimeout(r, seconds * 1000))\n }\n }\n\n async connect() {}\n async disconnect() {}\n\n async rpc(params: ClientTransportRpcCall): Promise<ClientTransportRpcResult> {\n const { service, procedure, payload, signal } = params\n const url = this.getURL(`api/${service}/${procedure}`)\n const body = this.client.format.encode(payload)\n\n const response = await fetch(url, {\n method: 'POST',\n body,\n signal,\n keepalive: true,\n credentials: 'include',\n cache: 'no-cache',\n headers: {\n 'Content-Type': this.client.format.contentType,\n Accept: this.client.format.contentType,\n ...(this.client.auth ? { Authorization: this.client.auth } : {}),\n },\n })\n\n if (!response.ok) {\n return {\n success: false,\n error: {\n code: ErrorCode.InternalServerError,\n data: { status: response.status, statusText: response.statusText },\n message: await response.text(),\n },\n }\n } else {\n const buf = await response.arrayBuffer()\n const { error, response: rpcResponse } = this.client.format.decode(buf)\n if (error) {\n return { success: false, error }\n } else {\n return { success: true, value: rpcResponse }\n }\n }\n }\n\n private getURL(path = '', params = '') {\n const url = new URL(path, this.options.origin)\n url.search = params\n return url\n }\n}\n"],"names":["ClientTransport","ErrorCode","TransportType","HttpClient","type","attempts","constructor","options","HTTP","healthCheck","signal","AbortSignal","timeout","url","getURL","ok","fetch","e","seconds","Math","min","Promise","r","setTimeout","connect","disconnect","rpc","params","service","procedure","payload","body","client","format","encode","response","method","keepalive","credentials","cache","headers","contentType","Accept","auth","Authorization","success","error","code","InternalServerError","data","status","statusText","message","text","buf","arrayBuffer","rpcResponse","decode","value","path","URL","origin","search"],"mappings":"AAAA,SACEA,eAAe,QAGV,gBAAe;AACtB,SAASC,SAAS,EAAEC,aAAa,QAAQ,gBAAe;AAiBxD,OAAO,MAAMC,mBAAmBH;;IAC9BI,KAAyB;IACjBC,SAAY;IA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IAAI,CAACR,SAASpB,EAAE,EAAE;YAChB,OAAO;gBACL8B,SAAS;gBACTC,OAAO;oBACLC,MAAM9C,UAAU+C,mBAAmB;oBACnCC,MAAM;wBAAEC,QAAQf,SAASe,MAAM;wBAAEC,YAAYhB,SAASgB,UAAU;oBAAC;oBACjEC,SAAS,MAAMjB,SAASkB,IAAI;gBAC9B;YACF;QACF,OAAO;YACL,MAAMC,MAAM,MAAMnB,SAASoB,WAAW;YACtC,MAAM,EAAET,KAAK,EAAEX,UAAUqB,WAAW,EAAE,GAAG,IAAI,CAACxB,MAAM,CAACC,MAAM,CAACwB,MAAM,CAACH;YACnE,IAAIR,OAAO;gBACT,OAAO;oBAAED,SAAS;oBAAOC;gBAAM;YACjC,OAAO;gBACL,OAAO;oBAAED,SAAS;oBAAMa,OAAOF;gBAAY;YAC7C;QACF;IACF;IAEQ1C,OAAO6C,OAAO,EAAE,EAAEhC,SAAS,EAAE,EAAE;QACrC,MAAMd,MAAM,IAAI+C,IAAID,MAAM,IAAI,CAACpD,OAAO,CAACsD,MAAM;QAC7ChD,IAAIiD,MAAM,GAAGnC;QACb,OAAOd;IACT;AACF"}
package/index.ts ADDED
@@ -0,0 +1,92 @@
1
+ import {
2
+ ClientTransport,
3
+ type ClientTransportRpcCall,
4
+ type ClientTransportRpcResult,
5
+ } from '@nmtjs/client'
6
+ import { ErrorCode, TransportType } from '@nmtjs/common'
7
+
8
+ export type ClientOptions = {
9
+ /**
10
+ * The origin of the server
11
+ * @example 'http://localhost:3000'
12
+ */
13
+ origin: string
14
+ debug?: boolean
15
+ }
16
+
17
+ export type HttpRpcOptions = {
18
+ timeout?: number
19
+ headers?: Record<string, string>
20
+ signal?: AbortSignal
21
+ }
22
+
23
+ export class HttpClient extends ClientTransport {
24
+ type = TransportType.HTTP
25
+ private attempts = 0
26
+
27
+ constructor(private readonly options: ClientOptions) {
28
+ super()
29
+ }
30
+
31
+ async healthCheck() {
32
+ while (true) {
33
+ try {
34
+ const signal = AbortSignal.timeout(10000)
35
+ const url = this.getURL('healthy')
36
+ const { ok } = await fetch(url, { signal })
37
+ if (ok) break
38
+ } catch (e) {}
39
+ this.attempts++
40
+ const seconds = Math.min(this.attempts, 15)
41
+ await new Promise((r) => setTimeout(r, seconds * 1000))
42
+ }
43
+ }
44
+
45
+ async connect() {}
46
+ async disconnect() {}
47
+
48
+ async rpc(params: ClientTransportRpcCall): Promise<ClientTransportRpcResult> {
49
+ const { service, procedure, payload, signal } = params
50
+ const url = this.getURL(`api/${service}/${procedure}`)
51
+ const body = this.client.format.encode(payload)
52
+
53
+ const response = await fetch(url, {
54
+ method: 'POST',
55
+ body,
56
+ signal,
57
+ keepalive: true,
58
+ credentials: 'include',
59
+ cache: 'no-cache',
60
+ headers: {
61
+ 'Content-Type': this.client.format.contentType,
62
+ Accept: this.client.format.contentType,
63
+ ...(this.client.auth ? { Authorization: this.client.auth } : {}),
64
+ },
65
+ })
66
+
67
+ if (!response.ok) {
68
+ return {
69
+ success: false,
70
+ error: {
71
+ code: ErrorCode.InternalServerError,
72
+ data: { status: response.status, statusText: response.statusText },
73
+ message: await response.text(),
74
+ },
75
+ }
76
+ } else {
77
+ const buf = await response.arrayBuffer()
78
+ const { error, response: rpcResponse } = this.client.format.decode(buf)
79
+ if (error) {
80
+ return { success: false, error }
81
+ } else {
82
+ return { success: true, value: rpcResponse }
83
+ }
84
+ }
85
+ }
86
+
87
+ private getURL(path = '', params = '') {
88
+ const url = new URL(path, this.options.origin)
89
+ url.search = params
90
+ return url
91
+ }
92
+ }
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@nmtjs/http-client",
3
+ "type": "module",
4
+ "module": "./dist/index.js",
5
+ "peerDependencies": {
6
+ "@nmtjs/common": "^0.0.1",
7
+ "@nmtjs/client": "^0.0.1"
8
+ },
9
+ "devDependencies": {
10
+ "@nmtjs/common": "^0.0.1",
11
+ "@nmtjs/client": "^0.0.1"
12
+ },
13
+ "files": [
14
+ "index.ts",
15
+ "dist",
16
+ "tsconfig.json",
17
+ "LICENSE.md",
18
+ "README.md"
19
+ ],
20
+ "version": "0.0.1",
21
+ "scripts": {
22
+ "build": "neemata-build -p neutral ./index.ts",
23
+ "type-check": "tsc --noEmit"
24
+ },
25
+ "types": "./index.ts"
26
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "lib": ["ESNEXT", "DOM"]
5
+ }
6
+ }