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

@mest-fe/cloudflare-workers-helper

v0.8.1

Published

Helper functions for Cloudflare Workers

Downloads

64

Readme

Cloudflare Workers Helpers

In Mest, we use Workers to handle the public endpoints of API services, which involves some standardized Response and common operations, and Helpers has summarized utils to reduce the amount of repetitive code in daily development.

To keep the script running fast, Helpers will only add simple functions or individual functions, and will only work with HTTP Workers.

Usage

  1. Install: yarn add @mest-fe/cloudflare-workers-helpers
  2. Import: import { utils } from '@mest-fe/cloudflare-workers-helpers'

Documentation

Utils

utils.textToHashHex

Convert text to hash hex string.

const hash = await utils.textToHashHex('hello world')

utils.standardizedUrl

Disassemble and extract the parts of the url.

const { pathname, query, url, relative } = utils.standardizedUrl(request)

utils.logger

Output logs, which are not parsed unless explicitly requested.

  • WORKERS_LOG: debug / info / undefined

Set the logging level using environment variables or global configuration:

// Set the logging level to `debug` in the global configuration
;(globalThis as any).WORKERS_LOG =
  // set the logging level to `debug` in the environment variables
  // wrangler.toml
  'debug'[vars]
WORKERS_LOG = 'debug'

Alias

Return the preset response as a shorthand named, option to cache requests or not.

Caching will only work on custom domains and each data center is isolated from each other.

Cache on Cloudflare

Basic

const handleRequest = (request: Request, event: FetchEvent) => {
  const alias = new Alias(request)
  return alias.noContent()
}

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request, event))
})

Cache response

Only a response can enter the cache after it has been consumed, and set cache does not block the http.

const handleRequest = (request: Request, event: FetchEvent) => {
  const alias = new Alias(request, {
    cache: { scope: 'my-scope', event },
  })
  // Return the cache directly if it exists
  const cache = alias.getCache()
  if (cache) return cache

  // ... some code

  // Cache 404 for 1 hour
  return alias.withCache(60 * 60).notFound()
}

Upstream

Forwarding requests upstream synchronously, with the ability to cache request returns in KV.

// -> http://localhost?q=hello
// <- https://www.google.com?q=hello

const upstream = new Upstream(request, {
  host: 'https://www.google.com',
})
return upstream.handler()

Modify content before request to upstream

You can usually modify the headers or endpoints before the request is initiated。

const upstream = new Upstream(request, {
  host: 'https://www.google.com',
  beforeRequest: ({ req, url }) => {
    const myUrl = url.replace('q=hello', 'q=world')
    const myReq = req.clone()
    myReq.headers.set('x-proxy-host', '...')
    return { req: myReq, url: myUrl }
  },
})
return upstream.handler()

If necessary, we can choose not to initiate this request and return a custom message.

new Upstream(request, {
  host: 'https://www.google.com',
  beforeRequest: ({ req, url }) => new Response('filtered'),
})

Cache to KV

Unlike the Alias that uses caches, Upstream can add KV as a persistent cache, which means that once a request is cached, it can get the same result in all data centers unless it expires or the version is manually updated.

The persistent cache will store the following sections of the response:

  • Response Body (with Content-Type and Content-Encoding)
  • Response headers (without cf-* and caches control headers)
  • Response status code

The persistent cache will set the ttl with the upstream header:

// upstream headers
headers = {
  'cache-control': 'max-age=3600',
}
const upstream = new Upstream(request, {
  host: 'https://www.google.com',
  KVCache: {
    KVNamespace: MY_KV_NAMESPACE,
    event,
  },
})

const cached = await upstream.getCache()
if (cached && !cached.expired) return cached.getResponse()

return upstream.withKVCache().handler()

If you want to track whether the request came from a cache, just add a custom header.

Images

Upload image

In general, it is recommended that you always manually specify the id of the image with the filename and keep it consistent, this will help you to distinguish the purpose of each image in the Cloudflare panel. Secondly, Cloudflare Images does not support updating images directly, so it would be helpful if we could create images with a fixed id to help us delete them.

const image = new Images({ apiToken, accountId })
const created = await image.uploadFromBlob(blob, {
  id: imageId,
  filename: imageId,
})

Delete image

const image = new Images({ apiToken, accountId })
const res = await image.removeImage(imageId)

Check image

Usually we want to verify the existence of the image through the api before deleting or uploading it.

const image = new Images({ apiToken, accountId })
const result = await image.hasImage(imageId)

License

MIT