{"id":15068253,"url":"https://github.com/alexkander/loopback-socket","last_synced_at":"2025-10-14T17:09:20.030Z","repository":{"id":42315515,"uuid":"118857524","full_name":"alexkander/loopback-socket","owner":"alexkander","description":"Loopback module for create Socket.io connections and allow call methods and make subscriptions","archived":false,"fork":false,"pushed_at":"2022-12-30T21:01:16.000Z","size":596,"stargazers_count":6,"open_issues_count":9,"forks_count":2,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-08-27T06:47:45.339Z","etag":null,"topics":["auth","events","express","expressjs","io","loopback","realtime","security","socket","strongloop","subscription","websocket"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alexkander.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-01-25T03:34:10.000Z","updated_at":"2022-02-11T13:34:28.000Z","dependencies_parsed_at":"2023-01-31T16:30:56.437Z","dependency_job_id":null,"html_url":"https://github.com/alexkander/loopback-socket","commit_stats":null,"previous_names":["arondn2/loopback-socket"],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/alexkander/loopback-socket","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexkander%2Floopback-socket","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexkander%2Floopback-socket/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexkander%2Floopback-socket/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexkander%2Floopback-socket/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alexkander","download_url":"https://codeload.github.com/alexkander/loopback-socket/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexkander%2Floopback-socket/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279020085,"owners_count":26086805,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-14T02:00:06.444Z","response_time":60,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["auth","events","express","expressjs","io","loopback","realtime","security","socket","strongloop","subscription","websocket"],"created_at":"2024-09-25T01:32:48.894Z","updated_at":"2025-10-14T17:09:19.998Z","avatar_url":"https://github.com/alexkander.png","language":"JavaScript","readme":"loopback-socket\n===============\n\n[![npm version](https://badge.fury.io/js/loopback-socket.svg)](https://badge.fury.io/js/loopback-socket) [![Build Status](https://travis-ci.org/arondn2/loopback-socket.svg?branch=master)](https://travis-ci.org/arondn2/loopback-socket)\n[![Coverage Status](https://coveralls.io/repos/github/arondn2/loopback-socket/badge.svg?branch=master)](https://coveralls.io/github/arondn2/loopback-socket?branch=master)\n\nLoopback module for create Socket.io connections and allow call methods.\n\n## Installation\n\n`npm install loopback-socket --save`\n\n## Usage\n\n### Server side\n\n#### Include\n```js\nconst LoopbackSocket = require('loopback-socket');\n```\n\n#### LoopbackSocket.get(name, [timeout])\n\nCreate or get a instance with a specific name.\n\n##### Arguments\n Name        | Type      | Description\n-------------|-----------|-------------\n `name`      | `string`  | Name to instance. Required\n `[timeout]` | `integer` | Time to wait authentication after establish connection before disconnect the socket. Optional.\n\n##### Example\n```js\nconst loopbackSocket = LoopbackSocket.get('name');\nconst loopbackSocket = LoopbackSocket.get('name', 2000);\n```\n\n#### loopbackSocket.start(io)\n\nConfigure authentication, callbacks and methods with a server socket.\n\n##### Arguments\n Name | Type     | Description\n------|----------|-------------\n `io` | `object` | Server Socket IO instance. Required.\n\n##### Example\n```js\nconst server = require('http').createServer();\nconst io = require('socket.io')(server);\nloopbackSocket.start(io);\n```\n\n#### loopbackSocket.auth(authentication)\n\nSet the function to authenticate connected sockets.\n\n##### Arguments\n Name             | Type                                 | Description\n------------------|--------------------------------------|-------------\n `authentication` | `autentication function` or `object` | Function called with `(socket, credentials, [cb])` arguments or object like `{ model: Model, method: methodName }` where `Model` is a class and `methodName` is one of its methods (defined or to be defined) like `autentication function`.\n\n##### Authentication function\n\nIf an error is thrown in this function or it return a false value then authentication fails. If argument `cb` is not defined then the returned value will be a the authentication response, and if this value is a promise, then it will be resolved before.\n\n Name          | Type       | Description\n---------------|------------|-------------\n `socket`      | `object`   | Socket connected. Required.\n `credentials` | `object`   | Credentials received. Required.\n `[cb]`        | `function` | Callback with `(err, success)` arguments to async return value with NodeJs callback style. Optional.\n\n##### Example\n```js\n// Authentication function with NodeJs callback style\nfunction customAuthentication(socket, credentials, cb) {\n  User.getUserByCredentials(credentials, cb);\n}\n\n// Authentication function with direct value returned o Promise style\nfunction customAuthentication(socket, credentials) {\n  return User.getUserByCredentials(credentials); // return data or a promise\n}\n\n// Direct setting\nloopbackSocket.auth(customAuthentication);\n\n// Setting through a Model\nfunction MyModel() {};\n\nloopbackSocket.auth({\n  model: MyModel,\n  method: 'customAuthentication'\n});\n\nMyModel.customAuthentication = authentication;\n```\n\n#### loopbackSocket.onConnected(handler)\n\nAdd a on connected handler.\n\n##### Arguments\n Name      | Type                          | Description\n-----------|-------------------------------|-------------\n `handler` | `handler function` or `object` | Function called with `(socket, credentials, [cb])` arguments or object like `{ model: Model, method: methodName }` where `Model` is a class and `methodName` is one of its methods (defined or to be defined) with like `handler function`.\n\n##### Handler function\n\nIf argument `cb` is not defined then the returned value will be a the handler response, and if this value is a promise, then it will be resolved before.\n\n Name          | Type       | Description\n---------------|------------|-------------\n `socket`      | `object`   | Socket connected. Required.\n `credentials` | `object`   | Credentials received. Required.\n `[cb]`        | `function` | Callback with `(err, success)` arguments to async return value with NodeJs callback style. Optional.\n\n##### Example\n```js\n// Authentication function with NodeJs callback style\nfunction customOnConnectedHandler(socket, credentials, cb) {\n  User.getUserByCredentials(credentials, cb);\n}\n\n// Authentication function with direct value returned o Promise style\nfunction customOnConnectedHandler(socket, credentials) {\n  return User.getUserByCredentials(credentials); // return data or a promise\n}\n\n// Direct adding\nloopbackSocket.onConnected(customOnConnectedHandler);\n\n// Adding through a Model\nfunction MyModel() {};\n\nloopbackSocket.onConnected({\n  model: MyModel,\n  method: 'customOnConnectedHandler'\n});\n\nMyModel.customOnConnectedHandler = customOnConnectedHandler;\n```\n\n#### loopbackSocket.removeOnConnected(handler)\n\nRemove a connected handler\n\n##### Arguments\n Name      | Type                   | Description\n-----------|------------------------|-------------\n `handler` | `function` or `object` | Function called with `(socket, credentials, [cb])` arguments or object like `{ model: Model, method: methodName }` where `Model` is a class and `methodName` is one of its methods (defined or to be defined) with like `handler function`.\n\n##### Example\n```js\n// Direct remove\nloopbackSocket.onConnected(customOnConnectedHandler);\n\n// Remove Model method\nfunction MyModel() {};\n\nloopbackSocket.removeOnConnected({\n  model: MyModel,\n  method: 'customOnConnectedHandler'\n});\n```\n\n#### loopbackSocket.defineMethod(methodName, method)\n\nDefine a method to call by socket connection or replace one existing.\n\n##### Arguments\n Name         | Type                          | Description\n--------------|-------------------------------|-------------\n `methodName` | `string`                      | Method name.\n `method`     | `method function` or `object` | Function called with `(socket, credentials, args, [cb])` arguments or object like `{ model: Model, method: methodName }` where `Model` is a class and `methodName` is one of its methods (defined or to be defined) with like `method function`.\n\n##### Method function\n\nIf argument `cb` is not defined then the returned value will be the method called reponse, and if this value is a promise, then it will be resolved before.\n\n Name          | Type       | Description\n---------------|------------|-------------\n `socket`      | `object`   | Socket connected. Required.\n `credentials` | `object`   | Credentials received. Required.\n `args`.       | `object`   | Arguments to call method. Required.\n `[cb]`        | `function` | Callback with `(err, success)` arguments to async return value with NodeJs callback style. Optional.\n\n##### Example\n```js\n/// Method function with NodeJs callback style\nfunction customMethod(socket, credentials, args, cb) {\n  let data;\n\n  // Option 1\n  cb(null, data); // Client receives { result: data }\n  \n  // Option 2\n  cb('myError');  // Client receives { error: 'myError' }\n\n}\n\n/// Method function with direct value returned o Promise style\nfunction customMethod(socket, credentials, args) {\n  let dataOrPromise;\n\n  // Option 1\n  return dataOrPromise; // Client receives { result: dataOrPromiseResolvedValue }\n\n  // Option 2\n  throw 'myError'; // Client receives { error: 'myError' }\n\n}\n\n// Direct definition\nloopbackSocket.defineMethod('customMethod', customMethod);\n\n\n// Definition through a Model\nfunction MyModel() {};\n\nloopbackSocket.defineMethod('customMethod', {\n  model: MyModel,\n  method: 'customMethod',\n});\n\nMyModel.customMethod = customMethod;\n\n```\n\n#### loopbackSocket.removeMethod(methodName)\n\nRemove a method of socket.\n\n##### Arguments\n Name      | Type        | Description\n-----------|-------------|-------------\n `methodName` | `string` | Method name to remove.\n\n##### Example\n```js\n// Direct remove\nloopbackSocket.onConnected('customMethod');\n```\n\n### Client side sample\n\n```js\nconst socket = io('http://localhost');\n\nsocket.on('connect', (socket) =\u003e {\n  // send credentials\n  socket.emit('authentication', credentials);\n});\n\nsocket.on('authenticated', (socket) =\u003e {\n  // socket authenticated\n});\n\nsocket.on('unauthorized', (socket) =\u003e {\n  // socket failed authentication\n});\n\nfunction callMyMethod() {\n  // Call a defined socket method\n  socket.emit('myMethod', {}, (response) =\u003e {\n    if (response.error) {\n      // Method return a error;\n      return;\n    }\n    // Method success;\n    console.log(response.result);\n  });\n}\n\n```\n\n### Samples\n\n#### Loopback + AngularJS:\n\nhttps://github.com/arondn2/loopback-socket/tree/master/examples/loopback\n\n## Troubles\n\nIf you have any kind of trouble with it, just let me now by raising an issue on the GitHub issue tracker here:\n\nhttps://github.com/arondn2/loopback-socket/issues\n\nAlso, you can report the orthographic errors in the READMEs files or comments. Sorry for that, I do not speak English.\n\n## Tests\n\n`npm test` or `npm run cover`\n\n## Contributing\n\nIn lieu of a formal style guide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falexkander%2Floopback-socket","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falexkander%2Floopback-socket","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falexkander%2Floopback-socket/lists"}