Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support newUniqueId and idFromString #36

Merged
merged 1 commit into from
Jul 6, 2023

Conversation

nathanclevenger
Copy link
Contributor

@nathanclevenger nathanclevenger commented Jun 26, 2023

This solves #21 and #29. If get() is called with an undefined id then it is generated with newUniqueId, and if an existing Cloudflare-generated 64-digit is passed in then idFromString is called instead of durable.idFromName(id)

@nathanclevenger
Copy link
Contributor Author

@kwhitley Here is an example I created that uses both of these new methods. The key advantage of this approach is that it's significantly faster for new IDs as there is no round-the-world check for existing DOs by a given name:

import { error, json, Router, withParams } from 'itty-router'
import { createDurable, withDurables } from '../../src' // from 'itty-durable'

const router = Router()

router
  .get('*', withDurables(), withParams)
  .get('/', ({ Fetcher }) => Fetcher.get().location())
  .get('/:id', ({ Fetcher, id }) => Fetcher.get(id).location())
  .get('/:id/:target+', ({ Fetcher, id, target }) => Fetcher.get(id).fetcher('https://' + target))


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

  async location() {
    const id = this.state.id.toString()
    const { colo } = await fetch('https://workers.cloudflare.com/cf.json').then(res => res.json())
    return { id, colo }
  }

  fetcher(url, options = {}) {
    return fetch(url, options)
  }
}


export default {
  fetch: (req, env, ctx) => router.handle(req, env, ctx).then(json).catch(error)
}

@kwhitley kwhitley merged commit f4af4e9 into kwhitley:v2.x Jul 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants