├── .github ├── dependabot.yml └── workflows │ └── test.yml ├── .gitignore ├── .npmignore ├── .nvmrc ├── LICENSE.txt ├── __tests__ └── client.ts ├── example.ts ├── package-lock.json ├── package.json ├── readme.md ├── src └── lib │ └── client.ts └── tsconfig.json /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "monthly" 12 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: test 5 | 6 | on: 7 | push: 8 | branches: [main] 9 | pull_request: 10 | branches: [main] 11 | merge_group: 12 | branches: [main] 13 | 14 | jobs: 15 | test: 16 | runs-on: ubuntu-latest 17 | 18 | strategy: 19 | matrix: 20 | node-version: [16, 18] 21 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 22 | 23 | steps: 24 | - uses: actions/checkout@v2 25 | - name: Use Node.js ${{ matrix.node-version }} 26 | uses: actions/setup-node@v2 27 | with: 28 | node-version: ${{ matrix.node-version }} 29 | cache: "npm" 30 | - run: npm ci 31 | - run: npm run build --if-present 32 | - run: npm test 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | npm-debug.log 4 | dist 5 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | npm-debug.log 4 | 5 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | v16 2 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /__tests__/client.ts: -------------------------------------------------------------------------------- 1 | import ActionheroNodeClient from "../src/lib/client"; 2 | import { spawn, ChildProcessWithoutNullStreams } from "child_process"; 3 | import * as path from "path"; 4 | 5 | const port = 5000; 6 | 7 | const connectionParams = { 8 | host: "0.0.0.0", 9 | port: port, 10 | timeout: 1000, 11 | }; 12 | 13 | let apiProcess: ChildProcessWithoutNullStreams; 14 | let client: ActionheroNodeClient; 15 | 16 | describe("integration", () => { 17 | beforeAll(async () => { 18 | process.chdir( 19 | path.join(__dirname, "..", "node_modules", "actionhero-socket-server"), 20 | ); 21 | apiProcess = spawn("npm", ["run", "dev"]); 22 | 23 | apiProcess.stdout.on("data", (data: string) => { 24 | console.log(`stdout: ${data}`); 25 | }); 26 | 27 | apiProcess.stderr.on("data", (data: string) => { 28 | console.error(`stderr: ${data}`); 29 | }); 30 | 31 | apiProcess.on("close", (code: number) => { 32 | console.log(`child process exited with code ${code}`); 33 | }); 34 | 35 | await new Promise((resolve) => { 36 | setTimeout(resolve, 5000); 37 | }); 38 | }, 1000 * 10); 39 | 40 | afterAll(async () => { 41 | apiProcess.kill(); 42 | }); 43 | 44 | beforeEach(async () => { 45 | client = new ActionheroNodeClient(); 46 | await client.connect(connectionParams); 47 | }); 48 | 49 | afterEach(async () => { 50 | await client.disconnect(); 51 | }); 52 | 53 | it("actionhero server should have booted", () => { 54 | // api.should.be.an.instanceOf(Object); 55 | }); 56 | 57 | // it("can get my connection details", async () => { 58 | // const details = await client.detailsView(); 59 | // details.status.should.equal("OK"); 60 | // details.context.should.equal("response"); 61 | // details.data.totalActions.should.equal(0); 62 | // details.data.pendingActions.should.equal(0); 63 | // }); 64 | 65 | // it("should log server messages internally", async () => { 66 | // client.log.length.should.be.above(0); 67 | // client.log[0].data.welcome.should.equal( 68 | // "Hello! Welcome to the actionhero api" 69 | // ); 70 | // }); 71 | 72 | // it("should be able to set params", async () => { 73 | // const { error, data } = await client.paramAdd("key", "value"); 74 | // should.not.exist(error); 75 | // data.status.should.equal("OK"); 76 | 77 | // const { error: error2, data: data2 } = await client.paramView("key"); 78 | // should.not.exist(error2); 79 | // data2.data.should.equal("value"); 80 | 81 | // const { error: error3, data: data3 } = await client.paramsView(); 82 | // should.not.exist(error3); 83 | // data3.data.key.should.equal("value"); 84 | // }); 85 | 86 | // it("can delete params and confirm they are gone", async () => { 87 | // const { error } = await client.paramAdd("key", "value"); 88 | // should.not.exist(error); 89 | 90 | // const { error: error2, data: data2 } = await client.paramsDelete(); 91 | // should.not.exist(error2); 92 | // data2.status.should.equal("OK"); 93 | 94 | // const { error: error3, data: data3 } = await client.paramsView(); 95 | // should.not.exist(error3); 96 | // should.not.exist(data3.data.key); 97 | // }); 98 | 99 | // it("can delete a param and confirm they are gone", async () => { 100 | // const { error: error1 } = await client.paramAdd("key", "v1"); 101 | // should.not.exist(error1); 102 | 103 | // const { error: error2 } = await client.paramAdd("value", "v2"); 104 | // should.not.exist(error2); 105 | 106 | // const { error: error3 } = await client.paramDelete("key"); 107 | // should.not.exist(error3); 108 | 109 | // const { error: error4, data } = await client.paramsView(); 110 | // should.not.exist(error4); 111 | // Object.keys(data.data).length.should.equal(2); 112 | // should.exist(data.messageId); 113 | // data.data.value.should.equal("v2"); 114 | // }); 115 | 116 | // it("can run an action (success, simple params)", async () => { 117 | // const { error, data } = await client.action("status"); 118 | // should.not.exist(error); 119 | // data.uptime.should.be.above(0); 120 | // data.context.should.equal("response"); 121 | // }); 122 | 123 | // it("can run an action (failure, simple params)", async () => { 124 | // const { error, data } = await client.action("cacheTest"); 125 | // error.message.should.match(/key is a required parameter for this action/); 126 | // data.context.should.equal("response"); 127 | // }); 128 | 129 | // it("can run an action (success, complex params)", async () => { 130 | // var params = { key: "mykey", value: "myValue" }; 131 | // const { error, data } = await client.actionWithParams("cacheTest", params); 132 | // should.not.exist(error); 133 | // data.context.should.equal("response"); 134 | // data.cacheTestResults.saveResp.should.equal(true); 135 | // }); 136 | 137 | // it("can run an action (failure, complex params)", async () => { 138 | // var params = { key: "mykey", value: "v" }; 139 | // const { error, data } = await client.actionWithParams("cacheTest", params); 140 | // error.message.should.match(/inputs should be at least 3 letters long/); 141 | // data.context.should.equal("response"); 142 | // }); 143 | 144 | // it("can join a room", async () => { 145 | // await client.roomAdd("defaultRoom"); 146 | // const { data } = await client.roomView("defaultRoom"); 147 | // data.data.room.should.equal("defaultRoom"); 148 | // data.data.membersCount.should.equal(1); 149 | // Object.keys(data.data.members).length.should.equal(1); 150 | // Object.keys(data.data.members)[0].should.equal(client.id); 151 | // }); 152 | 153 | // it("can leave a room", async () => { 154 | // const { error: error1, data: data1 } = await client.detailsView(); 155 | // should.not.exist(error1); 156 | // data1.rooms.length.should.equal(0); 157 | 158 | // const { error: error2 } = await client.roomAdd("defaultRoom"); 159 | // should.not.exist(error2); 160 | 161 | // const { error: error3, data: data3 } = await client.roomView("defaultRoom"); 162 | // should.not.exist(error3); 163 | // Object.keys(data3.data.members).should.containEql(client.id); 164 | 165 | // const { error: error4 } = await client.roomLeave("defaultRoom"); 166 | // should.not.exist(error4); 167 | 168 | // const { error: error5, data: data5 } = await client.detailsView(); 169 | // should.not.exist(error5); 170 | // data5.rooms.length.should.equal(0); 171 | // }); 172 | 173 | // it("will translate bad status to an error callback", async () => { 174 | // const { error } = await client.roomView("someCrazyRoom"); 175 | // error.message.should.equal("connection not in this room (someCrazyRoom)"); 176 | // }); 177 | 178 | // it("will get SAY events", async () => { 179 | // await client.roomAdd("defaultRoom"); 180 | 181 | // await new Promise((resolve) => { 182 | // client.on("say", (message) => { 183 | // client.removeAllListeners("say"); 184 | // message.message.should.equal("TEST MESSAGE"); 185 | // return resolve(); 186 | // }); 187 | 188 | // api.chatRoom.broadcast({}, "defaultRoom", "TEST MESSAGE"); 189 | // }); 190 | // }); 191 | 192 | // it("will obey timeouts", async () => { 193 | // try { 194 | // await client.actionWithParams("sleepTest", { sleepDuration: 2 * 1000 }); 195 | // throw new Error("should not get here"); 196 | // } catch (error) { 197 | // error.should.match(/Timeout reached/); 198 | // } 199 | // }); 200 | 201 | // it("will obey timeouts again", async () => { 202 | // try { 203 | // await client.actionWithParams("sleepTest", { sleepDuration: 2 * 1000 }); 204 | // throw new Error("should not get here"); 205 | // } catch (error) { 206 | // error.should.match(/Timeout reached/); 207 | // } 208 | // }); 209 | 210 | // it("can reconnect"); 211 | }); 212 | -------------------------------------------------------------------------------- /example.ts: -------------------------------------------------------------------------------- 1 | // you will need an Actionhero server running the Actionhero Socket Server (https://github.com/actionhero/actionhero-socket-server) 2 | 3 | import ActionheroNodeClient from "./src/lib/client"; 4 | 5 | async function main() { 6 | const client = new ActionheroNodeClient(); 7 | 8 | client.on("say", (message) => { 9 | console.log(" > SAY: " + message.message + " | from: " + message.from); 10 | }); 11 | 12 | client.on("welcome", (welcome) => { 13 | console.log("WELCOME: " + welcome); 14 | }); 15 | 16 | client.on("error", (error) => { 17 | console.log("ERROR: " + error); 18 | }); 19 | 20 | client.on("end", () => { 21 | console.log("Connection Ended"); 22 | }); 23 | 24 | client.on("timeout", (request) => { 25 | console.log(request + " timed out"); 26 | }); 27 | 28 | await client.connect({ host: "127.0.0.1", port: 5000 }); 29 | 30 | // get details about myself 31 | console.log("My Details: ", client.details); 32 | 33 | // try an action 34 | const params = { key: "mykey", value: "myValue" }; 35 | const { error, data, delta } = await client.actionWithParams( 36 | "cacheTest", 37 | params 38 | ); 39 | if (error) throw error; 40 | 41 | console.log("cacheTest action response: ", data); 42 | console.log(" ~ request duration: ", delta); 43 | 44 | // join a chat room and talk 45 | await client.roomAdd("defaultRoom"); 46 | await client.say("defaultRoom", "Hello from the actionheroClient"); 47 | await client.roomLeave("defaultRoom"); 48 | 49 | // leave 50 | await client.disconnect(); 51 | console.log("all done!"); 52 | } 53 | 54 | main(); 55 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "Evan Tahler ", 3 | "name": "actionhero-node-client", 4 | "description": "ActionHero client for other node.js servers to use", 5 | "version": "8.0.1", 6 | "homepage": "https://github.com/actionhero/actionhero-node-client", 7 | "repository": { 8 | "type": "git", 9 | "url": "git://github.com/actionhero/actionhero-node-client.git" 10 | }, 11 | "main": "dist/client.js", 12 | "license": "Apache-2.0", 13 | "keywords": [ 14 | "socket", 15 | "tcp", 16 | "actionhero", 17 | "client", 18 | "request" 19 | ], 20 | "engines": { 21 | "node": ">=12.0.0" 22 | }, 23 | "scripts": { 24 | "test": "echo 'TODO'", 25 | "pretest": "prettier --check __tests__ src", 26 | "prepare": "rm -rf dist && tsc --declaration" 27 | }, 28 | "dependencies": { 29 | "uuid": "^11.0.3" 30 | }, 31 | "devDependencies": { 32 | "@types/jest": "^29.5.4", 33 | "actionhero-socket-server": "^3.0.1", 34 | "jest": "^29.6.4", 35 | "prettier": "^3.0.3", 36 | "ts-jest": "^29.1.1", 37 | "ts-node": "^10.9.1", 38 | "typescript": "^5.2.2" 39 | }, 40 | "jest": { 41 | "testPathIgnorePatterns": [ 42 | "/tmp" 43 | ], 44 | "transform": { 45 | "^.+\\.ts?$": "ts-jest" 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # ActionheroNodeClient 2 | For one node.js servers talking to another ActionHero server, over the socket protocol. 3 | 4 | ![NPM Version](https://img.shields.io/npm/v/actionhero-node-client.svg?style=flat) ![Node Version](https://img.shields.io/node/v/actionhero-node-client.svg?style=flat) [![Greenkeeper badge](https://badges.greenkeeper.io/actionhero/actionhero-node-client.svg)](https://greenkeeper.io/) [![test](https://github.com/actionhero/actionhero-node-client/actions/workflows/test.yml/badge.svg)](https://github.com/actionhero/actionhero-node-client/actions/workflows/test.yml) 5 | 6 | This library makes it easy for one nodeJS process to talk to a remote [actionhero](https://www.actionherojs.com/) server. 7 | 8 | This library makes use of actionhero's TCP socket connections to enable fast, stateful connections. This library also allows for many concurrent and asynchronous requests to be running in parallel by making use of actionhero's message counter. 9 | 10 | **notes:** 11 | * This Library is a server-server communication library, and is NOT the same as the websocket client library that is generated via the actionhero server. 12 | * Node.js v8+ is required to use this package, as it uses `async/await`. 13 | 14 | ## Setup 15 | 16 | Installation should be as simple as: 17 | 18 | ```javascript 19 | npm install --save actionhero-node-client 20 | ``` 21 | 22 | and then you can include it in your projects with: 23 | 24 | ```javascript 25 | var ActionheroNodeClient = require("actionhero-node-client"); 26 | var client = new ActionheroNodeClient(); 27 | ``` 28 | 29 | Once you have included the ActionheroClient library within your project, you can connect like this: 30 | 31 | ```javascript 32 | await client.connect({ 33 | host: "127.0.0.1", 34 | port: "5000", 35 | }); 36 | ``` 37 | 38 | default options (which you can override) are: 39 | 40 | ```javascript 41 | var defaults = { 42 | host: "127.0.0.1", 43 | port: "5000", 44 | delimiter: "\r\n", 45 | logLength: 100, 46 | secure: false, 47 | timeout: 5000, 48 | reconnectTimeout: 1000, 49 | reconnectAttempts: 10, 50 | }; 51 | ``` 52 | ## Methods 53 | 54 | One you are connected (by waiting for the "connected" event or using the `connect` callback), the following methods will be available to you: 55 | 56 | * `await ActionheroNodeClient.connect()` 57 | * `await ActionheroNodeClient.disconnect()` 58 | * `{error, data, delta} = await ActionheroNodeClient.paramAdd(key, value)` 59 | * remember that both key and value must pass JSON.stringify 60 | * The return value will contain the response from the server (`data`), a possible error (`error`), and the response's duration (`delta`) 61 | * `{error, data, delta} = await ActionheroNodeClient.paramDelete(key)` 62 | * The return value will contain the response from the server (`data`), a possible error (`error`), and the response's duration (`delta`) 63 | * `{error, data, delta} = await ActionheroNodeClient.paramsDelete()` 64 | * The return value will contain the response from the server (`data`), a possible error (`error`), and the response's duration (`delta`) 65 | * `{error, data, delta} = await ActionheroNodeClient.paramView(key)` 66 | * The return value will contain the response from the server (`data`), a possible error (`error`), and the response's duration (`delta`) 67 | * `{error, data, delta} = await ActionheroNodeClient.paramsView()` 68 | * The return value will contain the response from the server (`data`), a possible error (`error`), and the response's duration (`delta`) 69 | * `{error, data, delta} = await ActionheroNodeClient.details()` 70 | * The return value will contain the response from the server (`data`), a possible error (`error`), and the response's duration (`delta`) 71 | * `{error, data, delta} = await ActionheroNodeClient.roomView(room)` 72 | * The return value will contain the response from the server (`data`), a possible error (`error`), and the response's duration (`delta`) 73 | * `{error, data, delta} = await ActionheroNodeClient.roomAdd(room)` 74 | * The return value will contain the response from the server (`data`), a possible error (`error`), and the response's duration (`delta`) 75 | * `{error, data, delta} = await ActionheroNodeClient.roomLeave(room)` 76 | * The return value will contain the response from the server (`data`), a possible error (`error`), and the response's duration (`delta`) 77 | * `{error, data, delta} = await ActionheroNodeClient.say(room, msg)` 78 | * `msg` can be a string or an Object 79 | * {error, data, delta} = await `ActionheroNodeClient.action(action)` 80 | * this action method will not set or unset any params, and use those already set by `paramAdd` 81 | * The return value will contain the response from the server (`data`), a possible error (`error`), and the response's duration (`delta`) 82 | * `ActionheroNodeClient.actionWithParams(action, param)` 83 | * this action will ignore any previously set params to the connection 84 | * params is a hash of this form `{key: "myKey", value: "myValue"}` 85 | * The return value will contain the response from the server (`data`), a possible error (`error`), and the response's duration (`delta`) 86 | 87 | ## Events 88 | 89 | ActionheroNodeClient will emit a few types of events (many of which are caught in the example below). Here are the events, and how you might catch them: 90 | 91 | * `client.on("connected")` 92 | * `client.on("end")` 93 | * `client.on("welcome", (welcomeMessage) => {})` 94 | * welcomeMessage is a string 95 | * `client.on("error", (error) => {})` 96 | * errorMessage is a string 97 | * This is only emitted for connection errors, not errors to your requests/actions 98 | * `client.on("say", (message) => {})` 99 | * message is a hash containing `timeStamp`, `room`, `from`, and `message` 100 | * `client.on("timeout", (error, request, caller) => {})` 101 | * request is the string sent to the api 102 | * caller (the calling function) is also returned to with an error 103 | 104 | ## Data 105 | 106 | There are a few data elements you can inspect on `actionheroClient`: 107 | 108 | * `ActionheroNodeClient.lastLine` 109 | * This is the last parsed JSON message received from the server (chronologically, not by messageID) 110 | * `ActionheroNodeClient.userMessages` 111 | * a hash which contains the latest `say` message from all users 112 | * `ActionheroNodeClient.log` 113 | * An array of the last n parsable JSON replies from the server 114 | * each entry is of the form {data, timeStamp} where data was the server's full response 115 | * `ActionheroNodeClient.messageCount` 116 | * An integer counting the number of messages received from the server 117 | 118 | ## Example 119 | 120 | ```javascript 121 | var ActionheroNodeClient = require("actionhero-node-client"); 122 | 123 | async function main () { 124 | const client = new ActionheroNodeClient() 125 | 126 | client.on('say', (message) => { 127 | console.log(' > SAY: ' + message.message + ' | from: ' + message.from) 128 | }) 129 | 130 | client.on('welcome', (welcome) => { 131 | console.log('WELCOME: ' + welcome) 132 | }) 133 | 134 | client.on('error', (error) => { 135 | console.log('ERROR: ' + error) 136 | }) 137 | 138 | client.on('end', () => { 139 | console.log('Connection Ended') 140 | }) 141 | 142 | client.on('timeout', (request, caller) => { 143 | console.log(request + ' timed out') 144 | }) 145 | 146 | await client.connect({host: '127.0.0.1', port: '5000'}) 147 | 148 | // get details about myself 149 | console.log('My Details: ', client.details) 150 | 151 | // try an action 152 | const params = { key: 'mykey', value: 'myValue' } 153 | let {error, data, delta} = await client.actionWithParams('cacheTest', params) 154 | if (error) { throw error } 155 | console.log('cacheTest action response: ', data) 156 | console.log(' ~ request duration: ', delta) 157 | 158 | // join a chat room and talk 159 | await client.roomAdd('defaultRoom') 160 | await client.say('defaultRoom', 'Hello from the actionheroClient') 161 | await client.roomLeave('defaultRoom') 162 | 163 | // leave 164 | await client.disconnect() 165 | console.log('all done!') 166 | } 167 | 168 | main() 169 | 170 | ``` 171 | -------------------------------------------------------------------------------- /src/lib/client.ts: -------------------------------------------------------------------------------- 1 | import * as net from "net"; 2 | import * as tls from "tls"; 3 | import * as util from "util"; 4 | import * as uuid from "uuid"; 5 | import { EventEmitter } from "events"; 6 | 7 | export type ActionHeroNodeClientParams = { 8 | host?: string; 9 | port?: number; 10 | secure?: boolean; 11 | delimiter?: string; 12 | logLength?: number; 13 | timeout?: number; 14 | reconnectTimeout?: number; 15 | reconnectAttempts?: number; 16 | }; 17 | 18 | export default class ActionheroNodeClient extends EventEmitter { 19 | id: string; 20 | connected: boolean; 21 | connection: NodeJS.Socket; 22 | params: ActionHeroNodeClientParams; 23 | details: { [key: string]: string | number | boolean }; 24 | lastLine: { [key: string]: any }; 25 | stream: string; 26 | log: Array<{ timestamp: Date; data: any }>; 27 | reconnectAttempts: number; 28 | expectedResponses: { [key: string]: Function }; 29 | responseTimeouts: { [key: string]: NodeJS.Timeout }; 30 | startingTimeStamps: { [key: string]: number }; 31 | sending: boolean; 32 | 33 | constructor() { 34 | super(); 35 | 36 | this.id = null; 37 | this.connected = false; 38 | this.connection = null; 39 | this.params = { 40 | host: "127.0.0.1", 41 | port: 5000, 42 | delimiter: "\r\n", 43 | logLength: 10, 44 | secure: false, 45 | timeout: 5000, 46 | reconnectTimeout: 1000, 47 | reconnectAttempts: 10, 48 | }; 49 | this.details = null; 50 | this.lastLine = null; 51 | this.stream = ""; 52 | this.log = []; 53 | this.reconnectAttempts = 0; 54 | this.expectedResponses = {}; 55 | this.startingTimeStamps = {}; 56 | this.responseTimeouts = {}; 57 | this.sending = false; 58 | } 59 | 60 | async connect(params?: ActionHeroNodeClientParams) { 61 | if (this.connection) { 62 | delete this.connection; 63 | } 64 | 65 | if (params) { 66 | for (const k in params) { 67 | this.params[k] = params[k]; 68 | } 69 | } 70 | 71 | await new Promise((resolve) => { 72 | if (this.params.secure === true) { 73 | this.connection = tls.connect(this.params.port, this.params.host); 74 | } else { 75 | this.connection = net.connect(this.params.port, this.params.host); 76 | } 77 | this.connection.setEncoding("utf8"); 78 | 79 | this.connection.on("data", (chunk) => { 80 | this.emit("rawData", String(chunk)); 81 | this.stream += String(chunk); 82 | let delimited = false; 83 | if (this.stream.indexOf(this.params.delimiter) >= 0) { 84 | delimited = true; 85 | } 86 | 87 | if (delimited === true) { 88 | try { 89 | const lines = this.stream.split(this.params.delimiter); 90 | for (const j in lines) { 91 | const line = lines[j]; 92 | if (line.length > 0) { 93 | this.handleData(line); 94 | } 95 | } 96 | this.stream = ""; 97 | } catch (e) { 98 | this.lastLine = null; 99 | } 100 | } 101 | }); 102 | 103 | this.connection.on("connect", async (error) => { 104 | if (error) this.emit("error", error); 105 | 106 | this.connected = true; 107 | this.reconnectAttempts = 0; 108 | await this.detailsView(); 109 | this.emit("connected"); 110 | return resolve(null); 111 | }); 112 | 113 | this.connection.on("error", (error) => { 114 | this.emit("error", error); 115 | this.reconnect(); 116 | }); 117 | 118 | this.connection.on("end", () => { 119 | if (this.connected) { 120 | this.connected = false; 121 | } 122 | this.emit("end"); 123 | this.connection.removeAllListeners("data"); 124 | this.connection.removeAllListeners("error"); 125 | this.connection.removeAllListeners("end"); 126 | this.reconnect(); 127 | }); 128 | }); 129 | 130 | return this.details; 131 | } 132 | 133 | async reconnect() { 134 | this.reconnectAttempts++; 135 | 136 | if (this.reconnectAttempts > this.params.reconnectAttempts) { 137 | this.emit("error", new Error("maximin reconnectAttempts reached")); 138 | } else if ( 139 | this.connected === false && 140 | this.params.reconnectTimeout && 141 | this.params.reconnectTimeout > 0 142 | ) { 143 | await util.promisify(setTimeout)(this.params.reconnectTimeout); 144 | return this.connect(); 145 | } 146 | } 147 | 148 | async disconnect() { 149 | this.connected = null; 150 | this.send("exit"); 151 | return util.promisify(setTimeout)(10); 152 | } 153 | 154 | handleData(dataLine: string) { 155 | let line: {}; 156 | try { 157 | line = JSON.parse(dataLine); 158 | this.lastLine = line; 159 | } catch (e) { 160 | return this.emit("error", e, dataLine); 161 | } 162 | 163 | this.emit("data", line); 164 | this.addLog(line); 165 | 166 | // welcome message; indicates successful connection 167 | if (line["context"] === "api" && line["welcome"]) { 168 | return this.emit("welcome", line["welcome"]); 169 | } 170 | 171 | // "say" messages from other users 172 | if (line["context"] === "user") { 173 | return this.emit("say", { 174 | timeStamp: new Date(), 175 | message: line["message"], 176 | from: line["from"], 177 | }); 178 | } 179 | 180 | // responses to your actions 181 | if (line["context"] === "response") { 182 | const resolveResponse = this.expectedResponses[line["messageId"]]; 183 | if (resolveResponse) { 184 | clearTimeout(this.responseTimeouts[line["messageId"]]); 185 | const delta = 186 | new Date().getTime() - this.startingTimeStamps[line["messageId"]]; 187 | 188 | let error = null; 189 | if (line["error"]) { 190 | error = new Error(line["error"]); 191 | } else if (line["status"] && line["status"] !== "OK") { 192 | error = new Error(line["status"]); 193 | } 194 | 195 | resolveResponse({ error, data: line, delta }); 196 | 197 | delete this.expectedResponses[line["messageId"]]; 198 | delete this.startingTimeStamps[line["messageId"]]; 199 | delete this.responseTimeouts[line["messageId"]]; 200 | } 201 | } 202 | } 203 | 204 | send(string: string) { 205 | this.connection.write(string + "\r\n"); 206 | } 207 | 208 | async sleep(time: number) { 209 | await new Promise((resolve) => { 210 | setTimeout(resolve, time); 211 | }); 212 | } 213 | 214 | async awaitServerResponse(msg) { 215 | if (this.sending) { 216 | await this.sleep(10); 217 | return this.awaitServerResponse(msg); 218 | } else { 219 | if (!this.connected) { 220 | throw new Error("Not Connected"); 221 | } 222 | this.sending = true; 223 | 224 | const messageId = uuid.v4(); 225 | let response; 226 | try { 227 | this.send(`paramAdd messageId=${messageId}`); 228 | await this.sleep(1); 229 | this.send(msg); 230 | 231 | response = await new Promise((resolve, reject) => { 232 | this.expectedResponses[messageId] = resolve; 233 | this.startingTimeStamps[messageId] = new Date().getTime(); 234 | this.responseTimeouts[messageId] = setTimeout(() => { 235 | delete this.expectedResponses[messageId]; 236 | delete this.startingTimeStamps[messageId]; 237 | delete this.expectedResponses[messageId]; 238 | this.emit("timeout", msg); 239 | reject(new Error(`Timeout reached (${msg})`)); 240 | }, this.params.timeout); 241 | }); 242 | } finally { 243 | this.sending = false; 244 | } 245 | 246 | return response; 247 | } 248 | } 249 | 250 | async paramAdd(key: string, value: string) { 251 | if (!key) throw new Error("key is required"); 252 | if (!value) throw new Error("value is required"); 253 | 254 | return this.awaitServerResponse(`paramAdd ${key}=${value}`); 255 | } 256 | 257 | async paramDelete(key: string) { 258 | if (!key) throw new Error("key is required"); 259 | 260 | return this.awaitServerResponse(`paramDelete ${key}`); 261 | } 262 | 263 | async paramsDelete() { 264 | return this.awaitServerResponse("paramsDelete"); 265 | } 266 | 267 | async paramView(k: string) { 268 | return this.awaitServerResponse(`paramView ${k}`); 269 | } 270 | 271 | async paramsView() { 272 | return this.awaitServerResponse("paramsView"); 273 | } 274 | 275 | async detailsView() { 276 | const details = await this.awaitServerResponse("detailsView"); 277 | this.details = details.data; 278 | this.id = details.data.data.id; 279 | return details.data; 280 | } 281 | 282 | async roomAdd(room: string) { 283 | if (!room) throw new Error("room is required"); 284 | 285 | return this.awaitServerResponse(`roomAdd ${room}`); 286 | } 287 | 288 | async roomLeave(room: string) { 289 | if (!room) throw new Error("room is required"); 290 | 291 | return this.awaitServerResponse(`roomLeave ${room}`); 292 | } 293 | 294 | async roomView(room: string) { 295 | if (!room) throw new Error("room is required"); 296 | 297 | return this.awaitServerResponse(`roomView ${room}`); 298 | } 299 | 300 | async say(room: string, message: string) { 301 | if (!room) throw new Error("room is required"); 302 | if (!message) throw new Error("message is required"); 303 | 304 | return this.awaitServerResponse(`say ${room} ${message}`); 305 | } 306 | 307 | async action(action: string) { 308 | if (!action) throw new Error("action is required"); 309 | 310 | return this.awaitServerResponse(action); 311 | } 312 | 313 | async actionWithParams(action: string, params: { [key: string]: any }) { 314 | if (!action) throw new Error("action is required"); 315 | if (!params) throw new Error("params are required"); 316 | 317 | return this.awaitServerResponse(JSON.stringify({ action, params })); 318 | } 319 | 320 | async file(file: string) { 321 | if (!file) throw new Error("file is required"); 322 | 323 | this.awaitServerResponse(`file ${file}`); 324 | } 325 | 326 | addLog(entry: any) { 327 | this.log.push({ 328 | timestamp: new Date(), 329 | data: entry, 330 | }); 331 | 332 | while (this.log.length > this.params.logLength) { 333 | this.log.splice(0, 1); 334 | } 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "./dist", 4 | "allowJs": true, 5 | "module": "commonjs", 6 | "target": "es2018", 7 | "sourceMap": true 8 | }, 9 | "include": ["./src/**/*"] 10 | } 11 | --------------------------------------------------------------------------------