Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ts-raii-scope

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-raii-scope

TypeScript RAII proof of concept

  • 0.1.3
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
9
decreased by-86.76%
Maintainers
1
Weekly downloads
 
Created
Source

Introduction

RAII approach proof of concept in TypeScript, not for production use!

Installation

npm install ts-raii-scope

How to use

Let'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.

class Tmp implements IDisposable {
    private _dirPath: string;
    
    constructor() {
        this._dirPath = fs.mkdtempSync('prefix');
    }
    
    // methods for using this._dirPath
    // ...

    // Method to implement IDisposable interface
    public dispose(): void {
        fs.rmdirSync(this._dirPath);
    }
}

Disposing also could be made async:

    // Method to implement IDisposable interface
    public dispose(): Promise<any> {
        return new Promise((resolve, reject) => {
            fs.rmdir(this._dirPath, err => {
                err ? reject() : resolve();
            });
        });        
    }

You could also use DisposableResource from this package to get IDisposable object.

Ok, now usage of our Tmp class should looks like:

const tmp1 = new Tmp();
try {
    // ... use tmp1
    const tmp2 = new Tmp();
    try {
        // ... use tmp1, tmp2
        const tmp3 = new Tmp();
        try {
            // use tmp1, tmp2, tmp3
        }
        finally {
            tmp3.dispose();            
        }
    }
    finally {
      tmp2.dispose();
    }
}
finally {
  tmp1.dispose();  // or await tmp2.dispose() in case of async method
}

You should agree, it looks quite ugly with all that nested try ... finally blocks.

Here RaiiScope comes up to help us collect IDisposable resources and finally dispose them in a right order:

const raiiScope = new RaiiScope();
try {
    const tmp1 = raiiScope.push(new Tmp());
    // ... using tmp1
    const tmp2 = raiiScope.push(new Tmp());
    // ... using tmp1, tmp2
    const tmp3 = raiiScope.push(new Tmp());
    // ... using tmp1, tmp2, tmp3
}
finally {
    // or await raiiScope.dispose() in case of async method
    raiiScope.dispose();    
}

It works ok for all disposable classes: ones which do dispose() synchronously and ones which return Promise from dispose().

Another way to do the same:

RaiiScope.doInside(
    [new Tmp(), new Tmp(), new Tmp()], 
    (tmp1: Tmp, tmp2: Tmp, tmp3: Tmp) => {
       // ... using tmp1, tmp2, tmp3
    }
 );

RaiiScope.doInsideAsync() is available as well. It awaits method call inside and then awaits all dispose() calls.

Package provide one more kind of syntax sugar for using IDisposable resources in methods: @SyncRaiiMethodScope and @AsyncRaiiMethodScope decorators with the global raii object.

import { AsyncRaiiMethodScope, raii, SyncRaiiMethodScope } from 'ts-raii-scope';

class Example {
    @SyncRaiiMethodScope    
    public method(): string {
        // Decorator implicitly creates new RaiiScope for each 
        // method call and connects it to global raii
        
        const tmp1 = raii.push(new Tmp());
        const tmp2 = raii.push(new Tmp());
        const tmp3 = raii.push(new Tmp());
        
        // ... using tmp1, tmp2, tmp3
        
        // when execution goes out of scope (method returns, or throws exception)
        // tmp3.dispose(), tmp2.dispose(), tmp1.dispose() are called inside the  
        // created RaiiScope
    }
}

Decorator wraps method call in try ... finally and make global raii aware of method start and finish. But 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

    @AsyncRaiiMethodScope
    public async method(): Promise<string> {
        const asyncScope = raii.saveCurrentAsyncScope();
        
        const tmp1 = asyncScope.push(new Tmp());
        const tmp2 = asyncScope.push(new Tmp());            
        const tmp3 = asyncScope.push(new Tmp());
        
        // ... using tmp1, tmp2, tmp3
        // await ...
        // ... using tmp1, tmp2, tmp3 again
        
        // when result promise get resolved or rejected 
        // tmp3.dispose(), tmp2.dispose(), tmp1.dispose() are called inside 
        // asyncScope.dispose(), which is called by decorator
    }

Keywords

FAQs

Package last updated on 05 Mar 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc