Compare commits
82 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2e4adba867 | |||
| a6530e9752 | |||
| 7163c1dc67 | |||
| c2f4efd33d | |||
| bc7a828124 | |||
| f62497ce48 | |||
| 64e5f30bad | |||
| 1b41d5e3ad | |||
| c5954aa880 | |||
| b58d8084e9 | |||
| f765e60e1f | |||
| b726669c4b | |||
| 4f0066b5ca | |||
| 0edc903900 | |||
| fa41192377 | |||
| 725e3c65c6 | |||
| 4e9108f7df | |||
| 420d634e83 | |||
| eb596e5dd8 | |||
| 5748bd8280 | |||
| 4e8ea21df2 | |||
| 6f4be3baaa | |||
| a484060888 | |||
| c1b15daaca | |||
| f9397feaf0 | |||
| 889ec9c8ec | |||
| 5d460cf002 | |||
| 5e6ec0d311 | |||
| dd834590cc | |||
| 96b7354dae | |||
| 3a5533c4fe | |||
| 1f5f84763d | |||
| 6474112275 | |||
| a46c0cf395 | |||
| 8be5c352f4 | |||
| caaf947a46 | |||
| 2ec88494be | |||
| b80346d742 | |||
| aced21a968 | |||
| fa40e3a5dc | |||
| 9bb0008381 | |||
| 67bbea8811 | |||
| dc826cb65a | |||
| 1266a814c6 | |||
| 25a7397548 | |||
| 5009bec70c | |||
| d8d7b135f7 | |||
| 9738d88ec7 | |||
| 9d7f433685 | |||
| fc1124fb16 | |||
| 5e5f493dfa | |||
| 899a46f9de | |||
| 1412a06f4c | |||
| 51e6c5cf0e | |||
| 8d7eb3ff5f | |||
| a82f8ccc26 | |||
| d934f4b53b | |||
| 54b8a692ba | |||
| 2f39b5662d | |||
| 5b9e785159 | |||
| a5bca90eeb | |||
| 244016faed | |||
| 61719769a0 | |||
| 6e2855cf3c | |||
| 916052ef0b | |||
| 2f51e10fc4 | |||
| 6e2e2768e2 | |||
| 4c5abc89b8 | |||
| 5911d829f9 | |||
| eac735a691 | |||
| 4af7164a58 | |||
| 006073cbc8 | |||
| 7d8b41a5a6 | |||
| acca64fa31 | |||
| 1e570813a3 | |||
| 0199e8ef17 | |||
| 68def29c80 | |||
| 106eb12a7f | |||
| 5b868f1259 | |||
| 952835e46a | |||
| 5aa8048ce8 | |||
| 48112f97ce |
@@ -12,40 +12,36 @@ stages:
|
||||
- release
|
||||
- metadata
|
||||
|
||||
before_script:
|
||||
- pnpm install -g pnpm
|
||||
- pnpm install -g @shipzone/npmci
|
||||
- npmci npm prepare
|
||||
|
||||
# ====================
|
||||
# security stage
|
||||
# ====================
|
||||
# ====================
|
||||
# security stage
|
||||
# ====================
|
||||
mirror:
|
||||
stage: security
|
||||
script:
|
||||
- npmci git mirror
|
||||
only:
|
||||
- tags
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
auditProductionDependencies:
|
||||
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
||||
stage: security
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci command npm install --production --ignore-scripts
|
||||
- npmci command npm config set registry https://registry.npmjs.org
|
||||
- npmci command npm audit --audit-level=high --only=prod --production
|
||||
- npmci command npm config set registry https://registry.npmjs.org
|
||||
- npmci command pnpm audit --audit-level=high --prod
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
allow_failure: true
|
||||
|
||||
auditDevDependencies:
|
||||
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
||||
stage: security
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci command npm install --ignore-scripts
|
||||
- npmci command npm config set registry https://registry.npmjs.org
|
||||
- npmci command npm audit --audit-level=high --only=dev
|
||||
- npmci command pnpm audit --audit-level=high --dev
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
allow_failure: true
|
||||
|
||||
@@ -56,7 +52,6 @@ auditDevDependencies:
|
||||
testStable:
|
||||
stage: test
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci node install stable
|
||||
- npmci npm install
|
||||
- npmci npm test
|
||||
@@ -67,10 +62,9 @@ testStable:
|
||||
testBuild:
|
||||
stage: test
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci node install stable
|
||||
- npmci npm install
|
||||
- npmci command npm run build
|
||||
- npmci npm build
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- docker
|
||||
@@ -96,10 +90,9 @@ codequality:
|
||||
only:
|
||||
- tags
|
||||
script:
|
||||
- npmci command npm install -g tslint typescript
|
||||
- npmci command npm install -g typescript
|
||||
- npmci npm prepare
|
||||
- npmci npm install
|
||||
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
@@ -119,11 +112,9 @@ trigger:
|
||||
pages:
|
||||
stage: metadata
|
||||
script:
|
||||
- npmci node install lts
|
||||
- npmci command npm install -g @gitzone/tsdoc
|
||||
- npmci npm prepare
|
||||
- npmci node install stable
|
||||
- npmci npm install
|
||||
- npmci command tsdoc
|
||||
- npmci command npm run buildDocs
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
|
||||
24
.vscode/launch.json
vendored
24
.vscode/launch.json
vendored
@@ -2,28 +2,10 @@
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "current file",
|
||||
"type": "node",
|
||||
"command": "npm test",
|
||||
"name": "Run npm test",
|
||||
"request": "launch",
|
||||
"args": [
|
||||
"${relativeFile}"
|
||||
],
|
||||
"runtimeArgs": ["-r", "@gitzone/tsrun"],
|
||||
"cwd": "${workspaceRoot}",
|
||||
"protocol": "inspector",
|
||||
"internalConsoleOptions": "openOnSessionStart"
|
||||
},
|
||||
{
|
||||
"name": "test.ts",
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"args": [
|
||||
"test/test.ts"
|
||||
],
|
||||
"runtimeArgs": ["-r", "@gitzone/tsrun"],
|
||||
"cwd": "${workspaceRoot}",
|
||||
"protocol": "inspector",
|
||||
"internalConsoleOptions": "openOnSessionStart"
|
||||
"type": "node-terminal"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -2,17 +2,28 @@
|
||||
"gitzone": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "gitlab.com",
|
||||
"gitscope": "apiglobal",
|
||||
"githost": "code.foss.global",
|
||||
"gitscope": "api.global",
|
||||
"gitrepo": "typedsocket",
|
||||
"shortDescription": "a typedrequest extension supporting websockets",
|
||||
"npmPackagename": "@apiglobal/typedsocket",
|
||||
"description": "A library for creating typed WebSocket connections, supporting bi-directional communication with type safety.",
|
||||
"npmPackagename": "@api.global/typedsocket",
|
||||
"license": "MIT",
|
||||
"projectDomain": "api.global"
|
||||
"projectDomain": "api.global",
|
||||
"keywords": [
|
||||
"WebSocket",
|
||||
"Type Safety",
|
||||
"Real-time Communication",
|
||||
"Client-Server Architecture",
|
||||
"TypeScript",
|
||||
"Networking"
|
||||
]
|
||||
}
|
||||
},
|
||||
"npmci": {
|
||||
"npmGlobalTools": [],
|
||||
"npmAccessLevel": "public"
|
||||
},
|
||||
"tsdoc": {
|
||||
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
|
||||
}
|
||||
}
|
||||
26495
package-lock.json
generated
26495
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
46
package.json
46
package.json
@@ -1,32 +1,36 @@
|
||||
{
|
||||
"name": "@apiglobal/typedsocket",
|
||||
"version": "1.0.17",
|
||||
"name": "@api.global/typedsocket",
|
||||
"version": "3.0.1",
|
||||
"private": false,
|
||||
"description": "a typedrequest extension supporting websockets",
|
||||
"description": "A library for creating typed WebSocket connections, supporting bi-directional communication with type safety.",
|
||||
"main": "dist_ts/index.js",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"type": "module",
|
||||
"author": "Lossless GmbH",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"test": "(tstest test/ --web)",
|
||||
"build": "(tsbuild --web)"
|
||||
"build": "(tsbuild --web --allowimplicitany --skiplibcheck)",
|
||||
"buildDocs": "tsdoc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@gitzone/tsbuild": "^2.1.25",
|
||||
"@gitzone/tsbundle": "^1.0.80",
|
||||
"@gitzone/tstest": "^1.0.54",
|
||||
"@pushrocks/tapbundle": "^3.2.14",
|
||||
"@types/node": "^16.3.3",
|
||||
"tslint": "^6.1.3",
|
||||
"tslint-config-prettier": "^1.15.0"
|
||||
"@git.zone/tsbuild": "^2.1.66",
|
||||
"@git.zone/tsbundle": "^2.0.8",
|
||||
"@git.zone/tsrun": "^1.2.44",
|
||||
"@git.zone/tstest": "^1.0.77",
|
||||
"@push.rocks/smartenv": "^5.0.12",
|
||||
"@push.rocks/tapbundle": "^5.0.23",
|
||||
"@types/node": "^20.12.7"
|
||||
},
|
||||
"dependencies": {
|
||||
"@apiglobal/typedrequest": "^1.0.56",
|
||||
"@apiglobal/typedrequest-interfaces": "^1.0.15",
|
||||
"@pushrocks/isohash": "^1.0.2",
|
||||
"@pushrocks/smartexpress": "^3.0.102",
|
||||
"@pushrocks/smartsocket": "^1.2.8",
|
||||
"@pushrocks/smartstring": "^3.0.24"
|
||||
"@api.global/typedrequest": "^3.0.21",
|
||||
"@api.global/typedrequest-interfaces": "^3.0.18",
|
||||
"@push.rocks/isohash": "^2.0.0",
|
||||
"@push.rocks/smartjson": "^5.0.19",
|
||||
"@push.rocks/smartrx": "^3.0.7",
|
||||
"@push.rocks/smartsocket": "^2.0.25",
|
||||
"@push.rocks/smartstring": "^4.0.15",
|
||||
"@push.rocks/smarturl": "^3.0.5"
|
||||
},
|
||||
"browserslist": [
|
||||
"last 1 chrome versions"
|
||||
@@ -42,5 +46,13 @@
|
||||
"cli.js",
|
||||
"npmextra.json",
|
||||
"readme.md"
|
||||
],
|
||||
"keywords": [
|
||||
"WebSocket",
|
||||
"Type Safety",
|
||||
"Real-time Communication",
|
||||
"Client-Server Architecture",
|
||||
"TypeScript",
|
||||
"Networking"
|
||||
]
|
||||
}
|
||||
|
||||
4460
pnpm-lock.yaml
generated
Normal file
4460
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
1
readme.hints.md
Normal file
1
readme.hints.md
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
174
readme.md
174
readme.md
@@ -1,43 +1,159 @@
|
||||
# @apiglobal/typedsocket
|
||||
# @api.global/typedsocket
|
||||
a typedrequest extension supporting websockets
|
||||
|
||||
## Availabililty and Links
|
||||
* [npmjs.org (npm package)](https://www.npmjs.com/package/@apiglobal/typedsocket)
|
||||
* [gitlab.com (source)](https://gitlab.com/apiglobal/typedsocket)
|
||||
* [github.com (source mirror)](https://github.com/apiglobal/typedsocket)
|
||||
* [docs (typedoc)](https://apiglobal.gitlab.io/typedsocket/)
|
||||
## Install
|
||||
To install `@api.global/typedsocket` in your project, run the following command using npm:
|
||||
|
||||
## Status for master
|
||||
```bash
|
||||
npm install @api.global/typedsocket --save
|
||||
```
|
||||
|
||||
Status Category | Status Badge
|
||||
-- | --
|
||||
GitLab Pipelines | [](https://lossless.cloud)
|
||||
GitLab Pipline Test Coverage | [](https://lossless.cloud)
|
||||
npm | [](https://lossless.cloud)
|
||||
Snyk | [](https://lossless.cloud)
|
||||
TypeScript Support | [](https://lossless.cloud)
|
||||
node Support | [](https://nodejs.org/dist/latest-v10.x/docs/api/)
|
||||
Code Style | [](https://lossless.cloud)
|
||||
PackagePhobia (total standalone install weight) | [](https://lossless.cloud)
|
||||
PackagePhobia (package size on registry) | [](https://lossless.cloud)
|
||||
BundlePhobia (total size when bundled) | [](https://lossless.cloud)
|
||||
Platform support | [](https://lossless.cloud) [](https://lossless.cloud)
|
||||
For Yarn users:
|
||||
|
||||
```bash
|
||||
yarn add @api.global/typedsocket
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Use TypeScript for best in class intellisense.
|
||||
To utilize `@api.global/typedsocket` effectively, let's explore how to integrate it into a project with TypeScript. This guide provides comprehensive usage scenarios, highlighting all features of the module. `@api.global/typedsocket` extends the capabilities of `typedrequest` by integrating websocket support, allowing for real-time, bidirectional communication between a client and server.
|
||||
|
||||
TypedSocket is the typedrequest you love, just in a bidirectional way.
|
||||
### Getting Started
|
||||
|
||||
See the following examples from our test for reference:
|
||||
#### Prerequisites
|
||||
|
||||
## Contribution
|
||||
Before diving into examples, ensure you have the following:
|
||||
|
||||
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
|
||||
- A basic understanding of TypeScript and Node.js.
|
||||
- An existing project set up with TypeScript.
|
||||
- `@api.global/typedrequest` and its dependencies installed in your project.
|
||||
|
||||
For further information read the linked docs at the top of this readme.
|
||||
#### Initialization
|
||||
|
||||
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
|
||||
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
|
||||
First, let's import the required modules and initialize our server and client instances.
|
||||
|
||||
[](https://maintainedby.lossless.com)
|
||||
**Server Side:**
|
||||
|
||||
Within your server-side code, import and set up `TypedSocket` to create a websocket server.
|
||||
|
||||
```typescript
|
||||
import { TypedSocket } from '@api.global/typedsocket';
|
||||
import * as typedrequest from '@api.global/typedrequest';
|
||||
|
||||
// Initialize your TypedRouter
|
||||
const typedRouter = new typedrequest.TypedRouter();
|
||||
|
||||
// Create the TypedSocket server
|
||||
const server = await TypedSocket.createServer(typedRouter);
|
||||
|
||||
// Optionally, you can provide a smartexpressServerArg if you have an existing SmartExpress server
|
||||
```
|
||||
|
||||
**Client Side:**
|
||||
|
||||
On the client side, initialize `TypedSocket` to connect to the websocket server.
|
||||
|
||||
```typescript
|
||||
import { TypedSocket } from '@api.global/typedsocket';
|
||||
|
||||
// Assuming server is at http://localhost:3000
|
||||
const client = await TypedSocket.createClient(typedRouter, 'http://localhost:3000');
|
||||
```
|
||||
|
||||
### Defining Typed Requests
|
||||
|
||||
`@api.global/typedsocket` leverages `typedrequest` for type-safe requests and responses. Here's how you can define and handle typed requests:
|
||||
|
||||
**Defining a Typed Request Interface:**
|
||||
|
||||
Define an interface for the request and its corresponding response.
|
||||
|
||||
```typescript
|
||||
interface ExampleRequest extends typedrequestInterfaces.ITypedRequest {
|
||||
method: 'exampleMethod';
|
||||
request: {
|
||||
message: string;
|
||||
};
|
||||
response: {
|
||||
reply: string;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Handling Requests on the Server:**
|
||||
|
||||
Add a typed handler for the request in your `TypedRouter`.
|
||||
|
||||
```typescript
|
||||
typedRouter.addTypedHandler<ExampleRequest>(
|
||||
new typedrequest.TypedHandler('exampleMethod', async (requestData) => {
|
||||
return {
|
||||
reply: `Server received: ${requestData.message}`,
|
||||
};
|
||||
})
|
||||
);
|
||||
```
|
||||
|
||||
### Sending Requests from the Client
|
||||
|
||||
Use the client instance to send a request to the server and await a response.
|
||||
|
||||
```typescript
|
||||
const exampleRequest = client.createTypedRequest<ExampleRequest>('exampleMethod');
|
||||
const response = await exampleRequest.fire({
|
||||
message: 'Hello from client!',
|
||||
});
|
||||
|
||||
console.log(response.reply); // "Server received: Hello from client!"
|
||||
```
|
||||
|
||||
### Advanced Usage
|
||||
|
||||
#### Tagging Connections
|
||||
|
||||
For more refined control, especially in scenarios with multiple clients, you can tag connections for targeted communication.
|
||||
|
||||
```typescript
|
||||
// Add a tag to a client
|
||||
client.addTag('role', 'admin');
|
||||
|
||||
// On the server, find connections with the tag
|
||||
const adminConnections = await server.findAllTargetConnectionsByTag('role', 'admin');
|
||||
|
||||
// Send a message to all admin connections
|
||||
for (const adminConnection of adminConnections) {
|
||||
const request = server.createTypedRequest<ExampleRequest>('exampleMethod', adminConnection);
|
||||
await request.fire({
|
||||
message: 'Message to admins',
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Handling Reconnections
|
||||
|
||||
`TypedSocket` automatically attempts to reconnect in the event of connection loss. Ensure your server and client logic accounts for reconnection, especially for maintaining state or re-subscribing to necessary events.
|
||||
|
||||
### Conclusion
|
||||
|
||||
Implementing `@api.global/typedsocket` provides a type-safe, real-time communication layer for your TypeScript applications, extending the functionality of `typedrequest` into the realm of websockets. This guide covered initialization, defining typed requests, sending requests, and advanced usage patterns like tagging connections and handling reconnections.
|
||||
|
||||
Integrating `@api.global/typedsocket` into your project harnesses the power of websockets with the benefits of type safety and structured request/response patterns, enabling more reliable and maintainable real-time applications.
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
||||
|
||||
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
||||
|
||||
### Trademarks
|
||||
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
Registered at District court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { tap, expect } from '@pushrocks/tapbundle';
|
||||
import { tap, expect } from '@push.rocks/tapbundle';
|
||||
|
||||
import * as typedsocket from '../ts/index';
|
||||
import * as typedsocket from '../ts/index.js';
|
||||
|
||||
tap.test('should create a client', async () => {
|
||||
console.log('Browser test') // TODO: implement browser tests
|
||||
|
||||
72
test/test.ts
72
test/test.ts
@@ -1,21 +1,21 @@
|
||||
import { expect, tap } from '@pushrocks/tapbundle';
|
||||
import * as typedrequest from '@apiglobal/typedrequest';
|
||||
import * as typedrequestInterfaces from '@apiglobal/typedrequest-interfaces';
|
||||
import { expect, tap } from '@push.rocks/tapbundle';
|
||||
import * as typedrequest from '@api.global/typedrequest';
|
||||
import * as typedrequestInterfaces from '@api.global/typedrequest-interfaces';
|
||||
|
||||
import * as typedsocket from '../ts/index';
|
||||
import { request } from 'http';
|
||||
import * as typedsocket from '../ts/index.js';
|
||||
|
||||
interface IRequest_Client_Server extends typedrequestInterfaces.implementsTR<
|
||||
typedrequestInterfaces.ITypedRequest,
|
||||
IRequest_Client_Server
|
||||
> {
|
||||
interface IRequest_Client_Server
|
||||
extends typedrequestInterfaces.implementsTR<
|
||||
typedrequestInterfaces.ITypedRequest,
|
||||
IRequest_Client_Server
|
||||
> {
|
||||
method: 'sayhi';
|
||||
request: {
|
||||
greeting: string;
|
||||
};
|
||||
response: {
|
||||
answer: string
|
||||
}
|
||||
answer: string;
|
||||
};
|
||||
}
|
||||
|
||||
let testTypedSocketServer: typedsocket.TypedSocket;
|
||||
@@ -24,42 +24,52 @@ let testTypedSocketClient: typedsocket.TypedSocket;
|
||||
const testTypedRouter = new typedrequest.TypedRouter();
|
||||
|
||||
tap.test('should add some handlers', async () => {
|
||||
testTypedRouter.addTypedHandler<IRequest_Client_Server>(new typedrequest.TypedHandler('sayhi', async requestData => {
|
||||
return {
|
||||
answer: `ok, got it : ${requestData.greeting}`
|
||||
}
|
||||
}));
|
||||
})
|
||||
testTypedRouter.addTypedHandler<IRequest_Client_Server>(
|
||||
new typedrequest.TypedHandler('sayhi', async (requestData) => {
|
||||
return {
|
||||
answer: `ok, got it : ${requestData.greeting}`,
|
||||
};
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
tap.test('should create Server and Client', async (tools) => {
|
||||
testTypedSocketServer = await typedsocket.TypedSocket.createServer(testTypedRouter);
|
||||
testTypedSocketClient = await typedsocket.TypedSocket.createClient(testTypedRouter, 'http://localhost:3000');
|
||||
await tools.delayFor(1000);
|
||||
testTypedSocketClient = await typedsocket.TypedSocket.createClient(
|
||||
testTypedRouter,
|
||||
'http://localhost:3000'
|
||||
);
|
||||
console.log('test: waiting 5 seconds');
|
||||
await tools.delayFor(5000);
|
||||
await testTypedSocketServer.stop();
|
||||
|
||||
// lets create another server
|
||||
testTypedSocketServer = await typedsocket.TypedSocket.createServer(testTypedRouter);
|
||||
await tools.delayFor(60000);
|
||||
|
||||
// lets see if auto reconnect works
|
||||
console.log('test: waiting 21 seconds for reconnect');
|
||||
await tools.delayFor(21000);
|
||||
});
|
||||
|
||||
tap.test('should process messages from both sides', async () => {
|
||||
const myServerSideTypedRequest = testTypedSocketServer.createTypedRequest<IRequest_Client_Server>('sayhi');
|
||||
const myClientSideTypedRequest = testTypedSocketClient.createTypedRequest<IRequest_Client_Server>('sayhi');
|
||||
const myServerSideTypedRequest =
|
||||
testTypedSocketServer.createTypedRequest<IRequest_Client_Server>('sayhi');
|
||||
const myClientSideTypedRequest =
|
||||
testTypedSocketClient.createTypedRequest<IRequest_Client_Server>('sayhi');
|
||||
const response = await myClientSideTypedRequest.fire({
|
||||
greeting: 'that is a greeting from the client'
|
||||
greeting: 'that is a greeting from the client',
|
||||
});
|
||||
console.log(response);
|
||||
const response2 = await myServerSideTypedRequest.fire({
|
||||
greeting: 'that is a greeting from the server'
|
||||
greeting: 'that is a greeting from the server',
|
||||
});
|
||||
console.log(response2);
|
||||
})
|
||||
});
|
||||
|
||||
tap.test('should run without problems for a little bit', async tools => {
|
||||
await tools.delayFor(5000);
|
||||
})
|
||||
|
||||
tap.test('should disconnect', async () => {
|
||||
tap.test('should disconnect', async (tools) => {
|
||||
await testTypedSocketClient.stop();
|
||||
await testTypedSocketServer.stop();
|
||||
})
|
||||
tools.delayFor(1000).then(() => process.exit(0));
|
||||
});
|
||||
|
||||
tap.start();
|
||||
|
||||
8
ts/00_commitinfo_data.ts
Normal file
8
ts/00_commitinfo_data.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @pushrocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@api.global/typedsocket',
|
||||
version: '3.0.1',
|
||||
description: 'A library for creating typed WebSocket connections, supporting bi-directional communication with type safety.'
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
export * from './typedsocket.classes.typedsocket';
|
||||
export * from './typedsocket.classes.typedsocket.js';
|
||||
@@ -1,10 +1,9 @@
|
||||
import * as plugins from './typedsocket.plugins';
|
||||
import type * as smartexpress from '@pushrocks/smartexpress';
|
||||
import * as plugins from './typedsocket.plugins.js';
|
||||
|
||||
const publicRoleName = 'publicRoleName';
|
||||
const publicRolePass = 'publicRolePass';
|
||||
|
||||
export type TTypedSocketSide = 'server' | 'client';
|
||||
export type TTypedSocketSide = 'server' | 'client';
|
||||
|
||||
export class TypedSocket {
|
||||
// STATIC
|
||||
@@ -14,23 +13,19 @@ export class TypedSocket {
|
||||
*/
|
||||
public static async createServer(
|
||||
typedrouterArg: plugins.typedrequest.TypedRouter,
|
||||
smartexpressServerArg?: smartexpress.Server
|
||||
smartexpressServerArg?: any
|
||||
): Promise<TypedSocket> {
|
||||
const smartsocketServer = new plugins.smartsocket.Smartsocket({
|
||||
alias: 'typedsocketServer',
|
||||
port: 3000,
|
||||
});
|
||||
if (smartexpressServerArg) {
|
||||
smartsocketServer.setExternalServer('smartexpress', smartexpressServerArg);
|
||||
}
|
||||
const publicRole = new plugins.smartsocket.SocketRole({
|
||||
name: publicRoleName,
|
||||
passwordHash: await plugins.isohash.sha256FromString(publicRolePass),
|
||||
});
|
||||
smartsocketServer.addSocketRoles([publicRole]);
|
||||
|
||||
smartsocketServer.socketFunctions.add(
|
||||
new plugins.smartsocket.SocketFunction({
|
||||
funcName: 'processMessage',
|
||||
allowedRoles: [publicRole],
|
||||
funcDef: async (dataArg, socketConnectionArg) => {
|
||||
return typedrouterArg.routeAndAddResponse(dataArg);
|
||||
},
|
||||
@@ -50,14 +45,16 @@ export class TypedSocket {
|
||||
);
|
||||
targetConnectionArg = smartsocketServer.socketConnections.getArray()[0];
|
||||
} else {
|
||||
throw new Error('you need to specify the wanted targetConnection');
|
||||
throw new Error(
|
||||
'you need to specify the wanted targetConnection. Currently no target is selectable automatically.'
|
||||
);
|
||||
}
|
||||
}
|
||||
const response: T = await smartsocketServer.clientCall(
|
||||
const response: T = (await smartsocketServer.clientCall(
|
||||
'processMessage',
|
||||
dataArg,
|
||||
targetConnectionArg
|
||||
) as any;
|
||||
)) as any;
|
||||
return response;
|
||||
},
|
||||
smartsocketServer
|
||||
@@ -74,21 +71,18 @@ export class TypedSocket {
|
||||
): Promise<TypedSocket> {
|
||||
const domain = new plugins.smartstring.Domain(serverUrlArg);
|
||||
|
||||
const socketOptions = {
|
||||
const socketOptions: plugins.smartsocket.ISmartsocketClientOptions = {
|
||||
alias: aliasArg,
|
||||
role: publicRoleName,
|
||||
password: publicRolePass,
|
||||
port: domain.port || 3000,
|
||||
url: `${domain.nodeParsedUrl.protocol}//${domain.nodeParsedUrl.hostname}`,
|
||||
autoReconnect: true,
|
||||
}
|
||||
console.log(`starting typedsocket with the following settings:`)
|
||||
};
|
||||
console.log(`starting typedsocket with the following settings:`);
|
||||
console.log(socketOptions);
|
||||
const smartsocketClient = new plugins.smartsocket.SmartsocketClient(socketOptions);
|
||||
smartsocketClient.addSocketFunction(
|
||||
new plugins.smartsocket.SocketFunction({
|
||||
funcName: 'processMessage',
|
||||
allowedRoles: [],
|
||||
funcDef: async (dataArg, socketConnectionArg) => {
|
||||
return typedrouterArg.routeAndAddResponse(dataArg);
|
||||
},
|
||||
@@ -98,26 +92,38 @@ export class TypedSocket {
|
||||
'client',
|
||||
typedrouterArg,
|
||||
async <T extends plugins.typedrequestInterfaces.ITypedRequest>(dataArg: T): Promise<T> => {
|
||||
const response: T = (smartsocketClient.serverCall('processMessage', dataArg) as any) as T;
|
||||
const response: T = smartsocketClient.serverCall('processMessage', dataArg) as any as T;
|
||||
return response;
|
||||
},
|
||||
smartsocketClient
|
||||
);
|
||||
|
||||
console.log(`typedsocket triggering smartsocket to connect...`);
|
||||
const before = Date.now();
|
||||
await smartsocketClient.connect();
|
||||
console.log(`typedsocket triggered smartsocket connected in ${Date.now() - before}ms!!!`)
|
||||
|
||||
return typedsocket;
|
||||
}
|
||||
|
||||
public static useWindowLocationOriginUrl = () => {
|
||||
const windowLocationResult = plugins.smarturl.Smarturl.createFromUrl(globalThis.location.origin).toString();
|
||||
return windowLocationResult;
|
||||
}
|
||||
|
||||
// INSTANCE
|
||||
public side: TTypedSocketSide;
|
||||
public typedrouter: plugins.typedrequest.TypedRouter;
|
||||
public get eventSubject(): plugins.smartrx.rxjs.Subject<plugins.smartsocket.TConnectionStatus> {
|
||||
return this.socketServerOrClient.eventSubject;
|
||||
}
|
||||
private postMethod: plugins.typedrequest.IPostMethod &
|
||||
((
|
||||
typedRequestPostObject: plugins.typedrequestInterfaces.ITypedRequest,
|
||||
socketConnectionArg?: plugins.smartsocket.SocketConnection
|
||||
) => Promise<plugins.typedrequestInterfaces.ITypedRequest>);
|
||||
private socketServerOrClient: plugins.smartsocket.Smartsocket | plugins.smartsocket.SmartsocketClient;
|
||||
private socketServerOrClient:
|
||||
| plugins.smartsocket.Smartsocket
|
||||
| plugins.smartsocket.SmartsocketClient;
|
||||
constructor(
|
||||
sideArg: TTypedSocketSide,
|
||||
typedrouterArg: plugins.typedrequest.TypedRouter,
|
||||
@@ -130,12 +136,18 @@ export class TypedSocket {
|
||||
this.socketServerOrClient = socketServerOrClientArg;
|
||||
}
|
||||
|
||||
public addTag(keyArg: string, payloadArg: any) {
|
||||
if (this.side === 'client' && this.socketServerOrClient instanceof plugins.smartsocket.SmartsocketClient) {
|
||||
public addTag<T extends plugins.typedrequestInterfaces.ITag = any>(
|
||||
nameArg: T['name'],
|
||||
payloadArg: T['payload']
|
||||
) {
|
||||
if (
|
||||
this.side === 'client' &&
|
||||
this.socketServerOrClient instanceof plugins.smartsocket.SmartsocketClient
|
||||
) {
|
||||
this.socketServerOrClient.socketConnection.addTag({
|
||||
id: keyArg,
|
||||
payload: payloadArg
|
||||
})
|
||||
id: nameArg,
|
||||
payload: payloadArg,
|
||||
});
|
||||
} else {
|
||||
throw new Error('tagging is only supported on clients');
|
||||
}
|
||||
@@ -157,6 +169,11 @@ export class TypedSocket {
|
||||
return typedrequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns all matching target connection
|
||||
* @param asyncFindFuncArg
|
||||
* @returns
|
||||
*/
|
||||
public async findAllTargetConnections(
|
||||
asyncFindFuncArg: (connectionArg: plugins.smartsocket.SocketConnection) => Promise<boolean>
|
||||
) {
|
||||
@@ -173,31 +190,44 @@ export class TypedSocket {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* returns a single target connection by returning the first one of all matching ones
|
||||
* @param asyncFindFuncArg
|
||||
* @returns
|
||||
*/
|
||||
public async findTargetConnection(
|
||||
asyncFindFuncArg: (connectionArg: plugins.smartsocket.SocketConnection) => Promise<boolean>
|
||||
) {
|
||||
const allMatching = this.findAllTargetConnections(asyncFindFuncArg);
|
||||
const allMatching = await this.findAllTargetConnections(asyncFindFuncArg);
|
||||
return allMatching[0];
|
||||
}
|
||||
|
||||
public async findAllTargetConnectionsByTag(keyArg: string, payloadArg?: any) {
|
||||
return this.findAllTargetConnections(async socketConnectionArg => {
|
||||
public async findAllTargetConnectionsByTag<
|
||||
TTag extends plugins.typedrequestInterfaces.ITag = any
|
||||
>(keyArg: TTag['name'], payloadArg?: TTag['payload']) {
|
||||
return this.findAllTargetConnections(async (socketConnectionArg) => {
|
||||
let result: boolean;
|
||||
if (!payloadArg) {
|
||||
result = !!socketConnectionArg.getTagById('keyArg')
|
||||
result = !!(await socketConnectionArg.getTagById(keyArg));
|
||||
} else {
|
||||
result = !!socketConnectionArg.getTagById('keyArg') === payloadArg;
|
||||
result = !!(
|
||||
plugins.smartjson.stringify((await socketConnectionArg.getTagById(keyArg))?.payload) ===
|
||||
plugins.smartjson.stringify(payloadArg)
|
||||
);
|
||||
}
|
||||
return result;
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
public async findTargetConnectionByTag(keyArg: string, payloadArg?: any) {
|
||||
const allResults = this.findAllTargetConnectionsByTag(keyArg, payloadArg)
|
||||
public async findTargetConnectionByTag<TTag extends plugins.typedrequestInterfaces.ITag = any>(
|
||||
keyArg: TTag['name'],
|
||||
payloadArg?: TTag['payload']
|
||||
) {
|
||||
const allResults = await this.findAllTargetConnectionsByTag(keyArg, payloadArg);
|
||||
return allResults[0];
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
await this.socketServerOrClient.stop()
|
||||
await this.socketServerOrClient.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
// @apiglobal scope
|
||||
import * as typedrequest from '@apiglobal/typedrequest';
|
||||
import * as typedrequestInterfaces from '@apiglobal/typedrequest-interfaces';
|
||||
import * as typedrequest from '@api.global/typedrequest';
|
||||
import * as typedrequestInterfaces from '@api.global/typedrequest-interfaces';
|
||||
|
||||
export {
|
||||
typedrequest,
|
||||
typedrequestInterfaces,
|
||||
}
|
||||
export { typedrequest, typedrequestInterfaces };
|
||||
|
||||
// @pushrocks scope
|
||||
import * as isohash from '@pushrocks/isohash';
|
||||
import * as smartsocket from '@pushrocks/smartsocket';
|
||||
import * as smartstring from '@pushrocks/smartstring';
|
||||
import * as isohash from '@push.rocks/isohash';
|
||||
import * as smartjson from '@push.rocks/smartjson';
|
||||
import * as smartrx from '@push.rocks/smartrx';
|
||||
import * as smartsocket from '@push.rocks/smartsocket';
|
||||
import * as smartstring from '@push.rocks/smartstring';
|
||||
import * as smarturl from '@push.rocks/smarturl';
|
||||
|
||||
export {
|
||||
isohash,
|
||||
smartsocket,
|
||||
smartstring
|
||||
}
|
||||
export { isohash, smartjson, smartrx, smartsocket, smartstring, smarturl };
|
||||
|
||||
14
tsconfig.json
Normal file
14
tsconfig.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"esModuleInterop": true,
|
||||
"verbatimModuleSyntax": true
|
||||
},
|
||||
"exclude": [
|
||||
"dist_*/**/*.d.ts"
|
||||
]
|
||||
}
|
||||
17
tslint.json
17
tslint.json
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"extends": ["tslint:latest", "tslint-config-prettier"],
|
||||
"rules": {
|
||||
"semicolon": [true, "always"],
|
||||
"no-console": false,
|
||||
"ordered-imports": false,
|
||||
"object-literal-sort-keys": false,
|
||||
"member-ordering": {
|
||||
"options":{
|
||||
"order": [
|
||||
"static-method"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"defaultSeverity": "warning"
|
||||
}
|
||||
Reference in New Issue
Block a user