{"id":18586369,"url":"https://github.com/cardinalby/ts-raii-scope","last_synced_at":"2025-04-10T13:32:04.639Z","repository":{"id":57381043,"uuid":"173596614","full_name":"cardinalby/ts-raii-scope","owner":"cardinalby","description":"RAII proof of concept on TypeScript","archived":false,"fork":false,"pushed_at":"2020-07-12T06:03:13.000Z","size":10,"stargazers_count":8,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-02T16:03:38.024Z","etag":null,"topics":["destroy","idisposable","raii","ts","typescript"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cardinalby.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-03-03T16:01:21.000Z","updated_at":"2022-12-04T01:01:07.000Z","dependencies_parsed_at":"2022-09-26T16:41:17.906Z","dependency_job_id":null,"html_url":"https://github.com/cardinalby/ts-raii-scope","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cardinalby%2Fts-raii-scope","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cardinalby%2Fts-raii-scope/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cardinalby%2Fts-raii-scope/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cardinalby%2Fts-raii-scope/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cardinalby","download_url":"https://codeload.github.com/cardinalby/ts-raii-scope/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248225709,"owners_count":21068078,"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":["destroy","idisposable","raii","ts","typescript"],"created_at":"2024-11-07T00:38:02.956Z","updated_at":"2025-04-10T13:31:59.599Z","avatar_url":"https://github.com/cardinalby.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Build Status](https://travis-ci.com/cardinalby/ts-raii-scope.svg?branch=master)](https://travis-ci.com/cardinalby/ts-raii-scope)\n### Introduction\nRAII approach proof of concept in TypeScript, not for production use!\n### Installation\n`npm install ts-raii-scope`\n### How to use   \nLet's create class representing temporary dir. According to RAII object of this class should get acquisition of resource in constructor and be responsible of disposing (destroying) resource when the object is not more needed.\n```js\nclass Tmp implements IDisposable {\n    private _dirPath: string;\n    \n    constructor() {\n        this._dirPath = fs.mkdtempSync('prefix');\n    }\n    \n    // methods for using this._dirPath\n    // ...\n\n    // Method to implement IDisposable interface\n    public dispose(): void {\n        fs.rmdirSync(this._dirPath);\n    }\n}\n```\nDisposing also could be made async:\n```js\n    // Method to implement IDisposable interface\n    public dispose(): Promise\u003cany\u003e {\n        return new Promise((resolve, reject) =\u003e {\n            fs.rmdir(this._dirPath, err =\u003e {\n                err ? reject() : resolve();\n            });\n        });        \n    }\n``` \nYou could also use `DisposableResource` from this package to get `IDisposable` object.\n\nOk, now usage of our `Tmp` class should looks like:\n```js\nconst tmp1 = new Tmp();\ntry {\n    // ... use tmp1\n    const tmp2 = new Tmp();\n    try {\n        // ... use tmp1, tmp2\n        const tmp3 = new Tmp();\n        try {\n            // use tmp1, tmp2, tmp3\n        }\n        finally {\n            tmp3.dispose();            \n        }\n    }\n    finally {\n      tmp2.dispose();\n    }\n}\nfinally {\n  tmp1.dispose();  // or await tmp2.dispose() in case of async method\n}\n```\nYou should agree, it looks quite ugly with all that nested `try ... finally` blocks.\n \nHere `RaiiScope` comes up to help us collect `IDisposable` resources and finally dispose them in a right order:\n```js\nconst raiiScope = new RaiiScope();\ntry {\n    const tmp1 = raiiScope.push(new Tmp());\n    // ... using tmp1\n    const tmp2 = raiiScope.push(new Tmp());\n    // ... using tmp1, tmp2\n    const tmp3 = raiiScope.push(new Tmp());\n    // ... using tmp1, tmp2, tmp3\n}\nfinally {\n    // or await raiiScope.dispose() in case of async method\n    raiiScope.dispose();    \n}\n```\nIt works ok for all disposable classes: ones which do `dispose()` synchronously and ones which return `Promise` from `dispose()`. \n\nAnother way to do the same:\n```js\nRaiiScope.doInside(\n    [new Tmp(), new Tmp(), new Tmp()], \n    (tmp1: Tmp, tmp2: Tmp, tmp3: Tmp) =\u003e {\n       // ... using tmp1, tmp2, tmp3\n    }\n );\n```\n`RaiiScope.doInsideAsync()` is available as well. It `await`s method call inside and then `await`s all `dispose()` calls.\n\nPackage provide one more kind of syntax sugar for using `IDisposable` resources in methods: `@SyncRaiiMethodScope` and `@AsyncRaiiMethodScope` decorators with the global `raii` object.\n```js\nimport { AsyncRaiiMethodScope, raii, SyncRaiiMethodScope } from 'ts-raii-scope';\n\nclass Example {\n    @SyncRaiiMethodScope    \n    public method(): string {\n        // Decorator implicitly creates new RaiiScope for each \n        // method call and connects it to global raii\n        \n        const tmp1 = raii.push(new Tmp());\n        const tmp2 = raii.push(new Tmp());\n        const tmp3 = raii.push(new Tmp());\n        \n        // ... using tmp1, tmp2, tmp3\n        \n        // when execution goes out of scope (method returns, or throws exception)\n        // tmp3.dispose(), tmp2.dispose(), tmp1.dispose() are called inside the  \n        // created RaiiScope\n    }\n}\n``` \nDecorator wraps method call in `try ... finally` and make global `raii` aware of method start and finish.\nBut to make it works for async methods (which return `Promise` but continue use local variables in their scope in the future) we should use `@AsyncRaiiMethodScope` and save raii scope to use it in method\n```js\n    @AsyncRaiiMethodScope\n    public async method(): Promise\u003cstring\u003e {\n        const asyncScope = raii.saveCurrentAsyncScope();\n        \n        const tmp1 = asyncScope.push(new Tmp());\n        const tmp2 = asyncScope.push(new Tmp());            \n        const tmp3 = asyncScope.push(new Tmp());\n        \n        // ... using tmp1, tmp2, tmp3\n        // await ...\n        // ... using tmp1, tmp2, tmp3 again\n        \n        // when result promise get resolved or rejected \n        // tmp3.dispose(), tmp2.dispose(), tmp1.dispose() are called inside \n        // asyncScope.dispose(), which is called by decorator\n    }\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcardinalby%2Fts-raii-scope","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcardinalby%2Fts-raii-scope","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcardinalby%2Fts-raii-scope/lists"}