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

tswrap

v1.0.4

Published

Random assortment of Typescript utilities, wrappers, and types.

Downloads

30

Readme

tswrap

Random assortment of Typescript utilities, wrappers, and types.

Premise

Ditch the required usage of try/catch for async/await functions.

Return errors normally, utilise typescript types to force errors to be handled.

Usage

Install it: npm install tswrap --save

Require it: import * as tswrap from 'tswrap'

API

tswrap.R<ReturnType>

Shorthand for Promise<NodeJS.ErrnoException | T> Where T is a possible return type.

Best paired with an async function.

async function getItemById (id: string): tswrap.R<Item> {
  return database.lookup(id)
}

Functions marked with this return type always may return an error, and should be handled accordingly.

tswrap.RE

A utility function to mark that a function returns a promise that may return an error, but no other values you care about.

Equivalent to tswrap.R<null>.

tswrap.isError(value)

This function is used to check if the value returned from a function that has the return type of tswrap.R is an actual error.

If this function returns true, typescript knows the value is of type tswrap.E. If false, typescript knows the value is of the type T that was passed into tswrap.R<T>.

async function setPlayerConfirmedStatus (status: boolean): tswrap.R<Player> {
  ...
}

const playerUpdateResult = await setPlayerConfirmedStatus(true)

// playerUpdateResult type here is `tswrap.E | Player`
// Trying to access the variable as a `Player` will result in an error.

if (tswrap.isError(playerUpdateResult)) {
  // We have now narrowed the type of playerUpdateResult
  // to `tswrap.E`, and can handle that appropriately.
  console.error(`Error updating player: ${playerUpdateResult}`)
  return playerUpdateResult
}

// As long as we `return` from inside `isError`, typescript
// now knows that playerUpdateResult can no longer be `tswrap.E`,
// and as such, narrows the type back to `Player`.
console.log('Player email:', player.email)

tswrap.wrapPromise<ReturnType>(promise)

This function is used to wrap external promises that do not conform to the tswrap.R return type.

function updatePlayerEmail (id: string, email: string): Promise<Player> {
  return new Promise((resolve, reject) => {
    database.updatePlayer({ id }, { email }, (err, player) => {
      if (err) return reject(err)
      return resolve(player)
    })
  })
}

const playerUpdateResult = await tswrap.wrapPromise<Player>(updatePlayerEmail(id, player))

if (tswrap.isError(playerUpdateResult)) {
  ...
}

tswrap.wrapAxios<ReturnType>(promise)

Higher level wrapper for axios results.

Will return either an AxiosError, or an AxiosResponse<ReturnType> value.

See tswrap.isAxiosError for an example.

tswrap.isAxiosError(value)

Used to check if the response from tswrap.wrapAxios is an AxiosError.

interface Response { id: string }

const result = await tswrap.wrapAxios<Response>(axios.get('https://my.com/api'))

if (tswrap.isAxiosError(result)) {
  return result
}

// result.data is now typed to the parameter passed to `tswrap.wrapAxios`
console.log('Got ID:', result.data.id)

tswrap.parseData<ReturnType>(data, structure)

Used in conjunction with io-ts for doing runtime validation.

Wraps structure.decode() into a tswrap compliant function.

See tswrap.isParseError for an example.

tswrap.isParseError(value)

Used to check if the response from tswrap.parseData is an error.

const requestSchema = iots.interface({ id: iots.string })
type RequestSchemaType = iots.TypeOf<typeof requestSchema>

const request = { id: 123 }

const parsedData = tswrap.parseData<RequestSchemaType>(request, requestSchema)

if (tswrap.isParseError(parsedData)) {
  // parsedData here is the raw Left<iots.Errors, any>
  // allowing you to use your own reporters to return an error
  return parsedData
}

console.log('Got ID:', parsedData.id)