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

durabledocs

v0.7.4

Published

Simple document database wrapper on top of CloudFlare's global Durable Objects platform

Downloads

23

Readme

DurableDocs (Work in Progress)

This package is not suitable for use at this time!

It is currently being extracted from a larger project to a standalone package.

DurableDocs is a document abstraction on top of CloudFlare's Durable Objects platform.

GitHub license npm

// Make user
const user = await docs.create({
  username: "ExampleUser123",
  website: "example.com",
  createdAt: new Date()
})
// Anonymous post
const post = await docs.create({
  name: "Test post",
  // Anonymous, no author set;
  author: DurableDocs.ObjectId,
  replies: DurableDocs.List
});
// User replies to post
const reply = await docs.create({
  content: "Replied to post",
  author: user
});

// Associate reply to post
await post.refs.replies.addDoc(reply);

// Get username of each person who replied
const usernames: string[] = [];
for await (const reply of (post.refs.replies as List).documents()) {
  usernames.push((await reply.refs.author.data()).username);
}

// usernames: ["ExampleUser123"]

Installation

This package is in active development and the API is subject to change! It is currently being extracted from a larger project to a standalone module.

npm i durabledocs

Features

Keep track of your Durable Objects!

  • Behaves similar to a document database
  • Easily link documents together
  • Optional garbage collection of unused/orphaned documents
  • Iteratively process documents to keep memory usage low and prevent eviction

Wishlist / Planned Features

  • Simple document index for scans and queries
  • Expiring documents
  • Unlimited-sized documents (best for data, not blob file storage!)
  • Document collections
  • Reference non-DurableDocs objects from within DurableDocs objects
  • Custom functions for custom document behavior
  • Transactions

Use Cases

Useful in applications where:

  • Data can be split into a large number of individual documents
  • Documents are individually relatively small ( < 128KiB)
  • Single documents are used less than ~100 times/second

Building large applications is possible with careful planning, not unlike any application that uses Durable Objects extensively. Other Durable Objects and Workers that you write can interact with DurableDocs via its methods.

Configuration

The DurableDocData class is exported from the main package. Re-export it in your worker's main entrypoint:

// src/worker.ts
import { DurableDocs, DurableDocData } from "durabledocs";

type Env = {
  DURABLE_DOC_DATA: DurableObjectNamespace,
  DURABLE_DOC_KV: KVNamespace
}

// Worker entrypoint for development
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const docs = new DurableDocs(env.DURABLE_DOC_DATA, env.DURABLE_DOC_KV);
    const newDoc = await docs.create({
      name: "Document One",
      numbers: 1234,
      otherDoc: DurableDocs.ObjectId,
      users: {
        admins: DurableDocs.List,
        members: DurableDocs.List
      }
    });

    return new Response(null, { status: 200 });
  }
};

// Export for wrangler
export { DurableDocData };
# wrangler.toml

name = "example-worker"
compatibility_date = "2022-10-01"
minify = true

main = "./src/worker.ts"

# Generate your own namespace called DURABLE_DOC_KV
# https://developers.cloudflare.com/workers/wrangler/workers-kv/#create-a-kv-namespace-with-wrangler
kv_namespaces = [
  { binding = "DURABLE_DOC_KV", id = "<Your KV Namespace>" }
]

[durable_objects]
  bindings = [
    { name = "DURABLE_DOC_DATA", class_name = "DurableDocData" }
  ]

[[migrations]]
  tag = "v1" # Should be unique for each entry
  new_classes = ["DurableDocData"]

General example

Creating documents, adding them to other documents, and accessing values:

// Typescript

import { DurableDocs, DurableDocData } from "durabledocs";

// All DurableDocs instances access the same data if passed the same namespace
// env.DURABLE_DOC_DATA is of type DurableObjectNamespace
const docs = new DurableDocs(env.DURABLE_DOC_DATA, env.DURABLE_DOC_KV);
    
const newThread = await docs.create({
  title: "Lorem Ipsum",
  content: "Consectetur adipiscing elit",
  author: docs.ObjectId(),             // Anonymous, not set
  properties: {
    views: 0,
    isLocked: false,
    isStickied: false,
    createdAt: new Date()
  },
  replies: docs.List()
});

const reply = await docs.create({
  author: DurableDocs.ObjectId("111"),      // An existing user
  content: "Morbi ullamcorper dapibus metus, sed porttitor diam feugiat nec.",
  properties: {
    createdAt: new Date()
  }
});
// reply.id == "12345bca"

let replyIds = await (newThread.refs.replies as List).ids();
console.log(`Before: newThread reply ids: ${replyIds}`);

await newThread.refs.replies.addDoc(reply);

replyIds = await (newThread.refs.replies as List).ids();
console.log(`After: newThread reply ids: ${replyIds}`);

Output:

Before: newThread reply ids: []
After: newThread reply ids: ["12345bca"]

Later:

const replyId = "12345bca";
const replyParents = await docs.get(replyId).parents();

console.log(`This post is referenced in ${ replyParents.length } threads:`);
for await (const parentThread of replyParents.documents()) {
  const content = await parentThread.data();
  console.log({
    id: parentThread.id,
    content
  });
}

console.log(`Thread`);

Output:

This post is referenced in 1 threads:
{
  id: "00000823756911274871238",
  content: {
    title: "Lorem Ipsum",
    content: "Consectetur adipiscing elit",
    author: undefined,
    properties: {
      views: 5,
      isLocked: false,
      isStickied: false,
      createdAt: "2022-10-01T18:19:01.595Z"
    }
    replies: ["12345bca"]
  }
}