{"id":16461529,"url":"https://github.com/kisiwu/novice-socket","last_synced_at":"2026-01-12T13:58:54.376Z","repository":{"id":42924041,"uuid":"244208856","full_name":"kisiwu/novice-socket","owner":"kisiwu","description":"A way of building server side socket.io applications.","archived":false,"fork":false,"pushed_at":"2024-03-04T12:23:12.000Z","size":246,"stargazers_count":0,"open_issues_count":9,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-05-05T19:22:11.341Z","etag":null,"topics":["nodejs","socket-io","websockets"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","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/kisiwu.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-03-01T19:17:20.000Z","updated_at":"2024-05-20T13:55:24.450Z","dependencies_parsed_at":"2024-03-04T13:41:11.167Z","dependency_job_id":null,"html_url":"https://github.com/kisiwu/novice-socket","commit_stats":{"total_commits":27,"total_committers":2,"mean_commits":13.5,"dds":0.03703703703703709,"last_synced_commit":"6c457b69e6cc73750b87cc0e1783d45177e147ad"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kisiwu%2Fnovice-socket","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kisiwu%2Fnovice-socket/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kisiwu%2Fnovice-socket/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kisiwu%2Fnovice-socket/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kisiwu","download_url":"https://codeload.github.com/kisiwu/novice-socket/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246939237,"owners_count":20857922,"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","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":["nodejs","socket-io","websockets"],"created_at":"2024-10-11T11:08:29.943Z","updated_at":"2026-01-12T13:58:54.319Z","avatar_url":"https://github.com/kisiwu.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# @novice1/socket\n\nA way of building server side [socket.io](https://www.npmjs.com/package/socket.io) applications.\n\n## Installation\n\n```bash\n$ npm install @novice1/socket\n```\n\n## How to use\n\n### Basically\n\n```js\nconst { NspBuilder, createServerApp } = require('@novice1/socket');\nconst http = require('http').createServer();\n\n// create namespace and add events to it\nlet defaultNamespace = new NspBuilder() \n  .add('chat message', function(req, res, next) {\n    let msg = req.data[0];\n    console.log('message: ' + msg);\n    res.of().emit('chat message', msg);\n  })\n  .add('disconnecting', function(req, res, next) {\n    console.log('user disconnecting');\n  });\n\n// create application\nlet socketApp = createServerApp()\n  .onConnection((socket, nsp) =\u003e {\n    // socket.use(fn)\n    // socket.join(room[, callback])\n    // socket.disconnect(close)\n\n    // Inherited from EventEmitter (along with other methods not mentioned here). \n    // See Node.js documentation for the events module.\n    // socket.once(eventName, listener)\n    // socket.removeListener(eventName, listener)\n    // socket.removeAllListeners([eventName])\n    // socket.eventNames()\n\n    console.log('a user connected');\n  })\n  .onDisconnect((reason, socket, nsp) =\u003e {\n    console.log('user disconnected');\n  })\n  .link(defaultNamespace); // link namespace to the application\n\n// build the application\nsocketApp.build(http); \n\n// start server\nhttp.listen(3000, function(){\n  console.log('listening on *:3000');\n});\n```\n\n### Namespaces\n\n#### Settings\n\nWhen setting a namespace you can define the name otherwise it will be '/' by default\n\n```js\nconst { NspBuilder } = require('@novice1/socket');\n\nlet defaultNamespace = new NspBuilder(); // same as new NspBuilder('/')\n\nlet appNamespace = new NspBuilder('/app');\n```\n\n#### Add events\n\nYou can add an event listener to a namespace with the method 'add'. It uses the method chaining pattern.\nThe first argument is the event's name. The other arguments must be the functions to execute. Multiple functions can be executed.\nEach function receives three parameters:\n- the [request context](#####requestcontext)\n- a [response object](#####responseobject)\n- a callback to optionally defer execution to the next function\n\n```js\nconst { NspBuilder } = require('@novice1/socket');\n\nlet appNamespace = new NspBuilder('/app')\n  .add('my event', function one(req, res, next) {\n    // do something\n    next(); // defer execution to the next function ('two')\n  }, function two(req, res) {\n    // do something\n  });\n\n// also\nappNamespace.add({\n  name: 'event name',\n  description: 'short description',\n  tags: ['Example']\n}, function(req, res) {\n  // do something\n})\n```\n\n##### \u003ca id=\"requestcontext\"\u003e\u003c/a\u003e request context\n\nIt is an object with the following properties:\n\n- **data** : Array of data sent through the event\n- **event** : the event's details (*name, description, tags*)\n- **nsp** : [Namespace](https://socket.io/docs/v4/server-api/#Namespace)\n- **socket** : [Socket](https://socket.io/docs/v4/server-api/#Socket)\n- **handshake** : [*Socket.handshake*](https://socket.io/docs/v4/server-api/#socket-handshake)\n\n\n##### \u003ca id=\"responseobject\"\u003e\u003c/a\u003e response object\n\nCan be used to emit an event from a socket, a room or a namespace\n\nExample\n\n```js\nconst { NspBuilder } = require('@novice1/socket');\n\nnew NspBuilder('/app')\n  .add('respond from socket', function one(req, res, next) {\n    let msg = req.data[0];\n\n    // examples from socket and room\n    res.emit('chat message', msg);\n    res.volatile.emit('chat message', msg);\n    res.broadcast.emit('chat message', msg);\n    res.compressed.emit('chat message', msg);\n    res.notCompressed.emit('chat message', msg);\n    res.in('room1').emit('chat message', msg);\n    res.to('room1').emit('chat message', msg);\n  })\n  .add('respond from namespace', function(req, res) {\n    let msg = req.data[0];\n\n    // examples from namespaces and room\n    res.of().emit('chat message', msg); // from current namespace\n    res.of('/chat').emit('chat message', msg); // from '/chat' namespace\n    res.of().volatile.emit('chat message', msg);\n    res.of().local.emit('chat message', msg);\n    res.of().in('room1').emit('chat message', msg);\n    res.of().to('room1').emit('chat message', msg);\n  });\n```\n\n#### Add events with ListenerBuilder\n\nThe advantage with ListenerBuilder is that you can define the callback (ErrorController) to be called when you execute the \"next\" callback with an argument that evaluates to `true`. \n\nExample\n\n```js\nconst { NspBuilder, ListenerBuilder } = require('@novice1/socket');\n\nlet listenerBuilder = new ListenerBuilder(\n    'eventName',\n    (req, res, next) =\u003e {\n      if (req.data[0]) {\n        // not ok, call ErrorController\n        next(new Error('missing message'));\n      } else {\n        // ok, defer\n        next();\n      }\n    },\n    (req, res) =\u003e {\n      // done\n    }\n  ).setErrorController((err, req, res) =\u003e {\n    // not ok, do something\n  });\n\nnew NspBuilder('/app')\n  .add(listenerBuilder);\n```\n\n\n#### Register a middleware to a namespace\n\nExample\n\n```js\nconst { NspBuilder } = require('@novice1/socket');\n\nnew NspBuilder() \n  .use((socket, next) =\u003e {\n    if (socket.request.headers.cookie) {\n      return next();\n    }\n    next(new Error('Authentication error'));\n  })\n```\n\nSee [namespace.use(fn)](https://socket.io/docs/v4/server-api/#namespace-use-fn)\n\n#### Register a middleware to sockets\n\nRegister a middleware to all sockets of a namespace.\n\nExample\n\n```js\nconst { NspBuilder } = require('@novice1/socket');\n\nnew NspBuilder() \n  .add((socket, packet, next) =\u003e {\n    if (packet.doge === true) return next();\n    next(new Error('Not a doge error'));\n  })\n```\n\nSee [socket.use(fn)](https://socket.io/docs/v4/server-api/#socket-use-fn)\n\n#### Link namespaces\n\nA namespace can be linked to another namespace. That way the name of the one being linked will be the concatenation of the namespace linking it and its own. The first argument can also be another string to use in the concatenation.\n\nExample\n\n```js\nconst { NspBuilder, createServerApp } = require('@novice1/socket');\nconst http = require('http').createServer();\n\nlet main = new NspBuilder('/main');\n\nlet app = new NspBuilder('/app');\n\nmain.link('/v1', app);\n\ncreateServerApp()\n  .link(main) // same as link('/', main)\n  .build(http)\n// the namespaces created will be '/main' and '/main/v1/app'\n\nhttp.listen(3000, function(){\n  console.log('listening on *:3000');\n});\n```\n\n### Application\n\n#### Settings\n\nWhen setting the application, you link the namespaces that will be used to build the `socket.io` server.\nYou can also limit the namespaces used to build the server.\n\nExample\n\n```js\nconst { NspBuilder, createServerApp } = require('@novice1/socket');\n\nlet appNsp = new NspBuilder('/app');\nlet otherNsp = new NspBuilder();\n\ncreateServerApp()\n  .link(appNsp)\n  .link('/other', otherNsp);\n// the namespaces created will be '/app' and '/other'\n\ncreateServerApp(['/main']) // limit to '/main'\n  .link(appNsp)\n  .link('/other', otherNsp); // useless\n// the namespaces created will be '/main'\n```\n\n#### Build\n\nIt will build the `socket.io` server from a `http` server.\nThe settings (namespaces, etc ...) need to be set before the build.\n\n```js\nconst { NspBuilder, createServerApp } = require('@novice1/socket');\nconst http = require('http').createServer();\n\nlet appNsp = new NspBuilder('/app');\n\ncreateServerApp()\n  .link(app)\n  .build(http); // build socket.io server\n\nhttp.listen(3000, function(){\n  console.log('listening on *:3000');\n});\n```\n\n#### Events\n\nGet a description of events listened by namespaces with the property `events`.\n\n```js\nconst { createServerApp } = require('@novice1/socket');\n\nlet app = createServerApp();\n\n// do something\n\nconsole.log(app.events['/']);\n// displays an array of events listened in the namespace '/'\n```\n\n#### Active namespaces\n\nGet an array of the active namespaces (= created on the server) with the property `activeNamespaces`.\nYou can also get one [namespace](https://socket.io/docs/v4/server-api/#Namespace) with the method `getNamespace`.\n\n```js\nconst { createServerApp } = require('@novice1/socket');\nconst http = require('http').createServer();\n\nlet app = createServerApp();\n\n// do something\n\napp.build(http);\n\nconsole.log(app.activeNamespaces);\n// displays an array of strings\n\nlet nsp = app.getNamespace('/');\n// get namespace '/' from socket.io server\n```\n\n#### Destroy\n\nYou can disconnect all clients and stop handling future connections by executing the method `destroy`.\nTo rebuild the application you can call the method `build` with no arguments.\n\n```js\nconst { createServerApp } = require('@novice1/socket');\nconst http = require('http').createServer();\n\nlet app = createServerApp();\n\n// do something\n\napp.build(http);\n\nhttp.listen(3000, function(){\n  console.log('listening on *:3000');\n\n  app.destroy();\n  // all connections closed and no future connections \n\n  app.build();\n  // connection possible again\n});\n```\n\n#### Close\n\nCloses the Socket.IO server and the underlying HTTP server.\n\n\n## NspBuilder methods\n\n- **add(...fn) : this**\n- **add(string, ...fn) : this**\n- **add(object, ...fn) : this**\n- **add(...NspBuilder) : this** (_alias for \"link\"method_)\n- **add(string, ...NspBuilder) : this** (_alias for \"link\"method_)\n- **getPaths() : string[]**\n- **getEvents() : object**\n- **link(...NspBuilder) : this**\n- **link(string, ...NspBuilder) : this**\n- **use(...fn) : this**\n\n## Application methods\n\n- [**adapter**](https://socket.io/docs/v4/server-api/#server-adapter-value)\n- **add(...fn) : this**\n- **add(string, ...fn) : this**\n- **add(object, ...fn) : this**\n- **add(...NspBuilder) : this** (_alias for \"link\" method_)\n- **add(string, ...NspBuilder) : this** (_alias for \"link\"method_)\n- **build([http.Server|options]) : this**\n- **build(port|http.Server[, options]) : this**\n- [**close**](https://socket.io/docs/v4/server-api/#server-close-callback)\n- **destroy() : this**\n- **getNamespace(string) : [Namespace](https://socket.io/docs/v4/server-api/#Namespace)**\n- **link(...NspBuilder) : this**\n- **link(string, ...NspBuilder) : this**\n- **use(...fn) : this**\n- **onConnection(..fn) : this**\n- **onDisconnect(..fn) : this**\n\n\n## Utils\n\n### explodeData\n\n```js\nconst { NspBuilder, utils } = require('@novice1/socket');\nconst { explodeData } = utils;\n\nlet defaultNamespace = new NspBuilder() \n  .add('chat message', explodeData(function(msg) {\n    // - this.req\n    // - this.res\n    // - this.next\n    console.log('message: ' + msg);\n    this.res.of().emit('chat message', msg);\n  }));\n```\n\n### errorHandler\n\n```js\nconst { NspBuilder, utils } = require('@novice1/socket');\nconst { errorHandler } = utils;\n\nlet defaultNamespace = new NspBuilder() \n  .add('chat message', errorHandler(function(req, res) {\n    // do something that could throw an error\n  }, 'chat error'));\n  // a message will be emitted on 'chat error' if an Error is thrown\n```\n\nOther examples\n\n```js\nconst { NspBuilder, utils } = require('@novice1/socket');\nconst { errorHandler } = utils;\n\nlet defaultNamespace = new NspBuilder() \n  .add('chat message', errorHandler(explodeData(function(msg) {\n    // do something\n  }), 'chat error'));\n```\n\n\n## References\n\n- [Socket.IO](https://socket.io/)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkisiwu%2Fnovice-socket","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkisiwu%2Fnovice-socket","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkisiwu%2Fnovice-socket/lists"}