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

@prgma/using

v1.0.5

Published

Bringing Python's `with` to JS/TS.

Downloads

10

Readme

using

Bringing Python's with to JS/TS.

Rationale

Python's with syntax provides a concise, idiomatic, repeatable method of automatically performing setup and cleanup for an operation such as reading a file from disk, making a network request, or interacting with a database. In addition, it provides a single logical method of handling any errors that may arise.

Usage

To get started, create a context guard object with an enter method and (optionally) an exit method. The enter method should perform any required setup and return the value you'll be using:

import { using } from '@prgma/using';

const FileGuard = {
  enter() {
    // get handle
    const handle = fs.open('somefile');
    return handle;
  },
  exit(handle) {
    // close handle
    fs.close(handle);
  },
};

using(FileGuard, handle => {
  // do something with prepared handle
  console.log(handle);
});

Functional Form

If you prefer a more functional approach, you can instead provide a function that returns the value to use and (optionally) a cleanup function. If you're returning both, make sure to wrap them in an array:

import { using } from '@prgma/using';

function open(path: string) {
  return function() {
    // get handle
    const handle = fs.open(path);
    return [
      handle,
      handle => {
        // close handle
        fs.close(handle);
      },
    ];
  };
}

using(open('foo.txt'), handle => {
  // do something with prepared handle
  console.log(handle);
});

Asynchronous Setup/Cleanup

Setup and cleanup processes generally require some form of interaction with external services, which is often made simpler by using an async function. Object context guards may have enter return a Promise that resolves to the value to use, which will work as you would expect:

import { using } from '@prgma/using';

async function getApiMessageForUser(userId: number): Promise<string> {
  return `Hello, user ${userId}!`;
}

function getMessage(userId: number): ContextGuards<string> {
  return {
    async enter() {
      const message = await getApiMessageForUser(userId);
      return message;
    },
    exit() {
      // cleanup
    },
  };
}

using(getMessage(1), message => {
  // do something with fetched message
  console.log(message);
});

exit may also be async - if so, you can await the entire using call, which will resolve when the cleanup has finished.

(async () => {
  await using(withAsyncCleanup, () => {/* ... */});
  console.log('cleanup finished!');
})();

Included Guards

Filesystem (using/fs)

The included open guard works just like Python's open - provide a file path and access flags ('r' by default) to get a file descriptor ready to use and automatically cleaned up upon completion:

import { using } from '@prgma/using';
import { open } from '@prgma/using/fs';
import * as fs from 'fs';

using(open('foo.txt', 'rw'), fd => {
  fs.write(fd, 'Hello, world!');
});