npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ts-raii-scope

v0.1.3

Published

TypeScript RAII proof of concept

Downloads

23

Readme

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
    }