{"id":16773835,"url":"https://github.com/ziflex/disposable-decorator","last_synced_at":"2025-10-05T16:02:09.075Z","repository":{"id":57212969,"uuid":"72474575","full_name":"ziflex/disposable-decorator","owner":"ziflex","description":"Wraps all custom type methods for checking whether an instance of the type is disposed","archived":false,"fork":false,"pushed_at":"2025-09-24T18:25:44.000Z","size":84,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-09-24T19:30:26.419Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","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/ziflex.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","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,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2016-10-31T20:19:57.000Z","updated_at":"2025-09-24T18:25:46.000Z","dependencies_parsed_at":"2025-10-05T16:00:49.226Z","dependency_job_id":null,"html_url":"https://github.com/ziflex/disposable-decorator","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ziflex/disposable-decorator","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ziflex%2Fdisposable-decorator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ziflex%2Fdisposable-decorator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ziflex%2Fdisposable-decorator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ziflex%2Fdisposable-decorator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ziflex","download_url":"https://codeload.github.com/ziflex/disposable-decorator/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ziflex%2Fdisposable-decorator/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":278477816,"owners_count":25993540,"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-05T02:00:06.059Z","response_time":54,"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":[],"created_at":"2024-10-13T06:47:09.907Z","updated_at":"2025-10-05T16:02:09.064Z","avatar_url":"https://github.com/ziflex.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# disposable-decorator\n\nA lightweight JavaScript decorator that automatically wraps object methods to check whether an instance has been disposed before allowing method execution. Perfect for implementing the dispose pattern in JavaScript classes.\n\n[![npm version](https://badge.fury.io/js/disposable-decorator.svg)](https://www.npmjs.com/package/disposable-decorator)\n[![Build Status](https://secure.travis-ci.org/ziflex/disposable-decorator.svg?branch=master)](http://travis-ci.org/ziflex/disposable-decorator)\n[![Coverage Status](https://coveralls.io/repos/github/ziflex/disposable-decorator/badge.svg?branch=master)](https://coveralls.io/github/ziflex/disposable-decorator)\n\n## Features\n\n- 🛡️ **Automatic disposal checks**: Prevents method calls on disposed objects\n- 🎯 **Smart method filtering**: Only decorates custom methods, preserves `constructor` and `isDisposed`\n- 📦 **Lightweight**: Zero dependencies, minimal footprint\n- 🔧 **Flexible**: Works with any class that implements `isDisposed()` method\n- ⚡ **Fast**: Minimal runtime overhead\n\n## Installation\n\n```bash\nnpm install --save disposable-decorator\n```\n\n## Quick Start\n\nThe decorator requires your class to implement an `isDisposed()` method that returns `true` when the object is disposed.\n\n```javascript\nconst disposableDecorator = require('disposable-decorator');\n\n// Your disposable class\nclass DatabaseConnection {\n    constructor(connectionString) {\n        this.connectionString = connectionString;\n        this.isConnected = true;\n        this._disposed = false;\n    }\n    \n    isDisposed() {\n        return this._disposed;\n    }\n    \n    dispose() {\n        this.isConnected = false;\n        this._disposed = true;\n    }\n    \n    query(sql) {\n        // This method will be protected after decoration\n        console.log(`Executing: ${sql}`);\n        return { results: [] };\n    }\n    \n    close() {\n        this.dispose();\n    }\n}\n\n// Apply the decorator to all methods\nObject.getOwnPropertyNames(DatabaseConnection.prototype).forEach(name =\u003e {\n    const descriptor = Object.getOwnPropertyDescriptor(DatabaseConnection.prototype, name);\n    if (descriptor \u0026\u0026 typeof descriptor.value === 'function') {\n        DatabaseConnection.prototype[name] = disposableDecorator(name, descriptor.value);\n    }\n});\n\n// Usage\nconst db = new DatabaseConnection('mongodb://localhost');\ndb.query('SELECT * FROM users'); // Works fine\n\ndb.dispose();\ndb.query('SELECT * FROM users'); // Throws: TypeError: Object is disposed\n```\n\n## Usage with compose-class\n\n```javascript\nimport composeClass from 'compose-class';\nimport DisposableMixin from 'disposable-mixin';\nimport disposableDecorator from 'disposable-decorator';\n\nconst Person = composeClass({\n    mixins: [\n        DisposableMixin()\n    ],\n\n    decorators: [\n        disposableDecorator\n    ],\n\n    constructor(name) {\n        this._name = name;\n    },\n\n    getName() {\n        return this._name;\n    },\n\n    setName(name) {\n        this._name = name;\n    }\n});\n\nconst instance = new Person('Mike Wazowski');\n\nconsole.log(instance.getName()); // 'Mike Wazowski'\n\ninstance.dispose();\n\nconsole.log(instance.getName()); // throws TypeError: 'Object is disposed'\n```\n\n## API Reference\n\n### disposableDecorator(methodName, originalMethod)\n\nCreates a decorated version of the provided method that checks for disposal before execution.\n\n**Parameters:**\n- `methodName` (string): The name of the method being decorated\n- `originalMethod` (function): The original method to wrap\n\n**Returns:**\n- (function): The decorated method that performs disposal checks\n\n**Behavior:**\n- If `methodName` is `'constructor'` or `'isDisposed'`, returns the original method unchanged\n- If `originalMethod` is not a function, returns it unchanged  \n- Otherwise, returns a wrapper function that:\n  1. Calls `this.isDisposed()` \n  2. Throws `TypeError('Object is disposed')` if disposed\n  3. Otherwise calls the original method with original arguments\n\n## Advanced Usage\n\n### Manual Method Decoration\n\n```javascript\nconst disposableDecorator = require('disposable-decorator');\n\nclass FileHandler {\n    constructor(filename) {\n        this.filename = filename;\n        this._disposed = false;\n    }\n    \n    isDisposed() {\n        return this._disposed;\n    }\n    \n    dispose() {\n        this._disposed = true;\n    }\n    \n    read() {\n        return `Reading ${this.filename}`;\n    }\n    \n    write(data) {\n        return `Writing to ${this.filename}: ${data}`;\n    }\n}\n\n// Manually decorate specific methods\nFileHandler.prototype.read = disposableDecorator('read', FileHandler.prototype.read);\nFileHandler.prototype.write = disposableDecorator('write', FileHandler.prototype.write);\n\nconst file = new FileHandler('config.json');\nconsole.log(file.read()); // Works\n\nfile.dispose();\nconsole.log(file.read()); // Throws: Object is disposed\n```\n\n### Using with ES6 Classes and Decorators\n\n```javascript\nconst disposableDecorator = require('disposable-decorator');\n\nfunction disposable(target) {\n    Object.getOwnPropertyNames(target.prototype).forEach(name =\u003e {\n        const descriptor = Object.getOwnPropertyDescriptor(target.prototype, name);\n        if (descriptor \u0026\u0026 typeof descriptor.value === 'function') {\n            target.prototype[name] = disposableDecorator(name, descriptor.value);\n        }\n    });\n    return target;\n}\n\n@disposable\nclass Service {\n    constructor() {\n        this._disposed = false;\n    }\n    \n    isDisposed() {\n        return this._disposed;\n    }\n    \n    dispose() {\n        this._disposed = true;\n    }\n    \n    doWork() {\n        return 'Working...';\n    }\n}\n```\n\n## How It Works\n\nThe decorator works by:\n\n1. **Method Inspection**: Examines the method name and type\n2. **Selective Wrapping**: Only wraps functions, ignoring properties and reserved methods\n3. **Runtime Checks**: Each decorated method calls `isDisposed()` before execution\n4. **Error Handling**: Throws `TypeError` with message \"Object is disposed\" when accessed after disposal\n\n### Reserved Methods\n\nThe following methods are never decorated:\n- `constructor` - Class constructor\n- `isDisposed` - Required method for disposal checking\n\n### Method Filtering\n\nThe decorator only wraps:\n- Properties that are functions\n- Methods that are not in the reserved list\n\nNon-function properties and reserved methods pass through unchanged.\n\n## Error Handling\n\nWhen a disposed object's method is called, a `TypeError` is thrown:\n\n```javascript\ntry {\n    disposedObject.someMethod();\n} catch (error) {\n    console.log(error instanceof TypeError); // true\n    console.log(error.message); // \"Object is disposed\"\n}\n```\n\n## Requirements\n\nYour class must implement:\n- `isDisposed()` method that returns a boolean indicating disposal state\n\n## Troubleshooting\n\n### Common Issues\n\n**Q: Methods are not being decorated**\nA: Ensure you're applying the decorator to function properties. The decorator ignores non-function properties.\n\n**Q: `isDisposed()` throws an error after disposal**\nA: The `isDisposed` method is never decorated and should always be callable, even after disposal.\n\n**Q: Constructor is being decorated**\nA: The `constructor` method is automatically excluded from decoration.\n\n**Q: Getting \"this.isDisposed is not a function\"**\nA: Your class must implement an `isDisposed()` method for the decorator to work.\n\n### Debugging\n\nEnable verbose error reporting:\n\n```javascript\nconst originalDecorator = require('disposable-decorator');\n\nfunction debuggingDecorator(name, fn) {\n    const decorated = originalDecorator(name, fn);\n    \n    if (decorated === fn) {\n        console.log(`Skipped decorating: ${name}`);\n        return fn;\n    }\n    \n    return function(...args) {\n        console.log(`Calling decorated method: ${name}`);\n        return decorated.apply(this, args);\n    };\n}\n```\n\n## License\n\nMIT © [Tim Voronov](https://github.com/ziflex)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fziflex%2Fdisposable-decorator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fziflex%2Fdisposable-decorator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fziflex%2Fdisposable-decorator/lists"}