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

itty-durable

v2.4.1

Published

Simplified interface for Cloudflare Durable Objects

Downloads

741

Readme

itty-durable

npm package Build Status Open Issues

Simplifies usage of Cloudflare Durable Objects, allowing lightweight object definitions and direct access to object methods from within Workers (no need for request building/handling).

Features

  • Removes nearly all boilerplate from writing and using Durable Objects.
  • Optional automatic non-blocking persistance layer
  • Optionally return contents from methods without explicit return (convenience feature)
  • Control how contents of object looks to outside requests
  • Control exactly what, if anything, is persisted
  • Already being used in production on high-availability/throughput apps like the Retheme browser extension!

Installation

npm install itty-router itty-durable

Example

Counter.js (your Durable Object class)
import { createDurable } from 'itty-durable'

export class Counter extends createDurable({ autoReturn: true }) {
  constructor(state, env) {
    super(state, env)

    // anything defined here is only used for initialization (if not loaded from storage)
    this.counter = 0
  }

  // Because this function does not return anything, it will return the entire contents
  // Example: { counter: 1 }
  increment() {
    this.counter++
  }

  // Any explicit return will honored, despite the autoReturn flag.
  // Note that any serializable params can passed through from the Worker without issue.
  add(a, b) {
    return a + b
  }
}
Worker.js (your CF Worker function)
import { ThrowableRouter, missing, withParams } from 'itty-router-extras'
import { withDurables } from 'itty-durable'

// export the durable class, per spec
export { Counter } from './Counter'

const router = ThrowableRouter({ base: '/counter' })

router
  // add upstream middleware, allowing Durable access off the request
  .all('*', withDurables())

  // get the durable itself... returns json response, so no need to wrap
  .get('/', ({ Counter }) => Counter.get('test').toJSON())

  // By using { autoReturn: true } in createDurable(), this method returns the contents
  .get('/increment', ({ Counter }) => Counter.get('test').increment())

  // you can pass any serializable params to a method... (e.g. /counter/add/3/4 => 7)
  .get('/add/:a?/:b?', withParams,
    ({ Counter, a, b }) => Counter.get('test').add(Number(a), Number(b))
  )

  // reset the durable
  .get('/reset', ({ Counter }) => Counter.get('test').reset())

  // 404 for everything else
  .all('*', () => missing('Are you sure about that?'))

// with itty, and using ES6 module syntax (required for DO), this is all you need
export default {
  fetch: router.handle
}

/*
Example Interactions:

GET /counter                                => { counter: 0 }
GET /counter/increment                      => { counter: 1 }
GET /counter/increment                      => { counter: 2 }
GET /counter/increment                      => { counter: 3 }
GET /counter/reset                          => { counter: 0 }
GET /counter/add/20/3                       => 23
*/

How it Works

This library works via a two part process:

  1. First of all, we create a base class for your Durable Objects to extend (through createDurable()). This embeds the persistance layer, a few convenience functions, and most importantly, a tiny internal itty-router to handle fetch requests. Using this removes the boilerplate from your objects themselves, allowing them to be only business logic.

  2. Next, we expose the withDurables() middleware for use within your Workers (it is designed for drop-in use with itty-router, but should work with virtually any typical Worker router). This embeds proxied stubs (translation: "magic stubs") into the Request. Using these stubs, you can call methods on the Durable Object directly, rather than manually creating fetch requests to do so (that's all handled internally, communicating with the embedded router within the Durable Objects themselves).

Installation

npm install itty-durable

API

createDurable(options?: object): class

Factory function to create the IttyDurable class (with options) for your Durable Object to extend.

| Option | Type(s) | Default | Description | | --- | --- | --- | --- | | autoPersist | boolean | false | By default, all contents are stored in-memory only, and are cleared when the DO evacuates from memory (unless explicitly asked to persist). By setting this to true, each request to the DO through the stub will persist the contents automatically. | autoReturn | boolean | false | If set to true, methods without an explicit return will return the contents of the object itself (as controlled through the toJSON() method). This method is overridable for custom payload shaping.

withDurables(options?: object): function

Highly-recommended middleware to embed itty-durable stubs into the request. Using these stubs allows you to skip manually creating/sending requests or handling response parsing.

| Option | Type(s) | Default | Description | | --- | --- | --- | --- | | parse | boolean | false | By default, the stub methods return a Promise to the Response from the Durable Object itself. This is great if you're just passing the response along and don't want to modify it. To take more control, setting this to true will instead return a Promise to the parsed JSON contents instead. To then respond to requests, you would have to handle building of a JSON Response yourself (e.g. json() within itty-router-extras).


Special Thanks

Big time thanks to all the fantastic developers on the Cloudflare Workers discord group, for their putting up with my constant questions, code snippets, and guiding me off the dangerous[ly flawed] path of async setters ;)

Contributors

Let's face it, in open source, these are the real heroes... improving the quality of libraries out there for everyone!

  • README tweaks, fixes, improvements: @tomByrer