Giter VIP home page Giter VIP logo

cloudflare-typescript-workers's Introduction

Cloudflare Workers with TypeScript and Webpack

Retired: as of 2022, Cloudflare's official types package @cloudflare/workers-types is more up-to-date and better supported.

Cloudflare Workers allow you to run JavaScript on Cloudflare's edge servers around the world. You can modify your site’s HTTP requests and responses, make parallel requests, or generate responses from the edge. This project develops, tests, and deploys NPM packages supporting the development of Cloudflare Workers using TypeScript.

Get started on your own TypeScript Cloudflare Worker using the Template.

  • types-cloudflare-worker - Complete types for all public features provided by Cloudflare Workers. Supports the Request.cf object, the Cache API and KV API.
  • cloudflare-worker-mock - Wraps service-worker-mock for name consistency, developer experience and to provide a simple mockable Cache API and KV API implementation.
  • @udacity/types-service-worker-mock - Incomplete types for the pinterest/service-worker-mock to support Cloudflare Worker Testing. May be pushed to the NPM @types project in the future, but needs additional work before that is reasonable.

The Cloudflare Worker API implements a subset of the Service Worker API specification, therefore Service Worker TypeScript types are a useful starting point.

Example

A small example of a strictly typed worker:

import CloudflareWorkerGlobalScope from 'types-cloudflare-worker';
declare var self: CloudflareWorkerGlobalScope;

export class Worker {
  public async handle(event: FetchEvent) {
    const originResponse = fetch(event.request, {
      cf: {
        minify: {
          html: true,
        },
      },
    });

    return originResponse;
  }
}

self.addEventListener('fetch', (event: FetchEvent) => {
  const worker = new Worker();
  event.respondWith(worker.handle(event));
});

Getting started

Start with the Starter Template or run the following commands:

npm init
# Add TypeScript
npm i -D \
  typescript \
  @types/node
# Setup the Cloudflare Worker Types and Mock
npm i -D \
  @udacity/types-service-worker-mock \
  types-cloudflare-worker \
  cloudflare-worker-mock

# Init TypeScript
tsc --init

Set the TypeScript compiler options in tsconfig.json:

"compilerOptions": {
  /* https://developers.cloudflare.com/workers/reference/ */
  /* Cloudflare Workers use the V8 JavaScript engine from Google Chrome. The
    * Workers runtime is updated at least once a week, to at least the version
    * that is currently used by Chrome’s stable release. This means you can
    * safely use latest JavaScript features, with no need for "transpilers".
    */
  "target": "ESNext",
  /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
  "module": "commonjs",
  /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
  "lib": ["esnext", "webworker"],
  /* Specify library files to be included in the compilation. */

  /* Recommend enabling all Strict Type-Checking Options and Additional Checks */
}

Building the Worker(s)

There are two implementations of the same test worker in this repository.

demo/src/helloworker.ts

This is the demo worker. It uses the published packages. Reference it as an example implementation and starting point for your project.

cd demo
npm i
jest
npm run build

src/helloworker.ts

This is the development worker. It uses the local packages.

npm i
jest
npm run build

Testing and deploying the packages

npm i
npm run test-all
scripts/publish.sh $VERSION $OTP # New version and 2FA

Author

Brad Erickson (@13rac1)

License

Licensed under the Apache License, Version 2.0.

© 2019 Udacity, Inc.

Content derived from Cloudflare Developer Documentation. © 2019 Cloudflare, Inc.

cloudflare-typescript-workers's People

Contributors

13rac1 avatar cjfinnell avatar dhaynespls avatar perangel avatar serceman avatar sodabrew avatar ziczhu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cloudflare-typescript-workers's Issues

Incompatible with service-worker-mock 2.0.5

service-worker-mock version 2.0.5 changed the signature for trigger('fetch', request) to return a single Response instead of Response[]. As a result, the type definitions are out of sync depending which version you are running.

Missing Dependency in cloudflare-worker-mock's package.json

It appears that cloudflare-worker-mock has a dependency on @udacity/types-service-worker-mock, which is not listed as a dependency in the package.json.

Requiring the module in JS gives this error:

Error: Cannot find module '@udacity/types-service-worker-mock/global'

Thanks for all your work on this!

Consider switching from to edge-mock

Hi, you might consider switching from service-worker-mock to edge-mock (which I've just built).

Just a suggestion, feel free to close this if you like.

A few advantages of edge-mock:

  1. service-workers the project which service-worker-mock is a part of is no longer maintained.
  2. edge-mock provides support for KV store mocking out-of-the-box
  3. edge-mock properly supports ArrayBuffer and ReadableStream which service-worker-mock do does not
  4. edge-mock has close to 100% test coverage and is written in typescript.
  5. All the implementations provided by edge-mock are fully compliant with the types they implement in typescript.

Cloning a response with new Response(response.body, response) discards headers

I have some test code that sets up a mock response like this:

fetchMock.mockResponse('', {
  headers: {
    'Content-Type': 'text/html'
  },
  status: 404
})

However, I noticed that my tests that were inspecting the Content-Type response header weren't behaving as expected. While debugging, I noticed that after I cloned the Response object with new Response(response.body, response), the resulting object did not have the response header. This seems to be the recommended way to clone the Response so that headers can be mutated, but I'm wondering if there's a way to get the test to behave the same way as Cloudflare does (keeping the headers in this circumstance).

Here's how you can see the issue in action if you run this code within a test:

const originalResponse = new Response('', {
  headers: {
    TestKey: 'TestValue'
  }
})
console.log('original', originalResponse.headers.get('TestKey'))

const clonedResponse = new Response(originalResponse.body, originalResponse)
console.log('cloned', clonedResponse.headers.get('TestKey'))

One possible workaround is to add code that does response.clone() when running a test instead of new Response(response.body, response), but that's not idea since it clutters the actual code. You can't use response.clone() in production because you still can't mutate the headers of the cloned Response object when you run the code in a real Cloudflare Worker.

Is there any way to get the test to behave more like Cloudflare Workers does?

KV Namespace list method signature confusion

The issue is with the list method signature (which is actually correct in the docblock above it).
NAMESPACE.list({prefix?: string, limit?: number, cursor?: string})

If I call the list method like this:
KVNAMESPACE.list('my_prefix').then((mylist) => {...
then it compiles but during execution it thorows the following error:
TypeError: Failed to execute 'list' on 'KvNamespace': parameter 1 is not of type 'ListOptions'.

If I call the list method like this:
KVNAMESPACE.list({prefix: 'my_prefix'}).then((mylist) => {...
then my code won't compile becasue I get:
Error:(35, 25) TS2345: Argument of type '{ prefix: string; }' is not assignable to parameter of type 'string'.

only if i do:

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
KVNAMESPACE.list({ prefix: prefix }).then((mylist) => {...

then it will run.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.