@cfworker/web
TypeScript icon, indicating that this package has built-in type declarations

5.0.5 • Public • Published

@cfworker/web

Web framework for Cloudflare Workers and service workers, inspired by Koa and fastify.

import {
  Application,
  Middleware,
  Router,
  validate,
  normalizePathnameMiddleware
} from '@cfworker/web';

const router = new Router();

// Add the homepage route.
router.get('/', ({ res }) => {
  res.body = `
    <h1>@cfworker/web demo</h1>
    <h2 id="example-routes">Example routes</h2>
    <ol aria-labelledby="example-routes">
      <li><a href="/greetings/hello">A valid greeting</a></li>
      <li><a href="/greetings/hell">An invalid greeting</a></li>
      <li><a href="/error">A route with a bug</a></li>
    </ol>
    <img src="favicon.ico" alt="cfworker logo">`;
});

// Add a greeting route with validation.
router.get(
  '/greetings/:greeting',
  validate({
    params: {
      required: ['greeting'],
      properties: {
        greeting: {
          minLength: 5,
          maxLength: 10
        }
      }
    }
  }),
  ({ req, res }) => {
    res.body = req.params;
  }
);

// Add a route to demonstrate exception handling.
router.get('/error', () => {
  // @ts-ignore - this route has a bug!
  req.this.method.does.not.exist();
});

// Favicon route for fun :)
router.get('/favicon.ico', ({ res }) => {
  res.type = 'image/svg+xml';
  res.body = `
      <svg xmlns="http://www.w3.org/2000/svg" baseProfile="full" width="200" height="200">
        <rect width="100%" height="100%" fill="#F38020"/>
        <text font-size="120" font-family="Arial, Helvetica, sans-serif" text-anchor="end" fill="#FFF" x="185" y="185">W</text>
      </svg>`;
});

// Simple CORS middleware.
const cors: Middleware = async ({ res }, next) => {
  res.headers.set('access-control-allow-origin', '*');
  await next();
};

// Compose the application
new Application()
  .use(normalizePathnameMiddleware)
  .use(cors)
  .use(router.middleware)
  .listen();

To run this example:

git clone https://github.com/cfworker/cfworker
cd cfworker
npm install
npm run start-web --workspace=@cfworker/examples

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
5.0.572latest

Version History

VersionDownloads (Last 7 Days)Published
5.0.572
5.0.471
5.0.311
5.0.24
5.0.11
5.0.01
4.0.13
4.0.03
3.0.03
2.1.03
2.0.01
1.14.0149
1.13.01
1.12.512
1.12.41
1.12.30
1.12.20
1.12.10
1.12.00
1.11.00
1.10.20
1.10.11
1.10.01
1.9.00
1.8.51
1.8.40
1.8.30
1.8.20
1.8.10
1.8.00
1.6.110
1.6.101
1.6.80
1.6.50
1.6.40
1.6.30
1.6.00
1.5.00
1.3.01
1.2.180
1.2.171
1.2.160
1.2.140
1.2.130
1.2.100
1.2.90
1.2.60
1.2.40
1.2.30
1.2.20
1.2.10
1.2.00
1.1.30
1.1.10
1.1.01
1.0.111
1.0.102
1.0.91
1.0.52

Package Sidebar

Install

npm i @cfworker/web

Weekly Downloads

349

Version

5.0.5

License

MIT

Unpacked Size

59.9 kB

Total Files

52

Last publish

Collaborators

  • jdanyow