Giter VIP home page Giter VIP logo

Comments (3)

lukeed avatar lukeed commented on July 3, 2024 3

Here's another approach that essentially combines (1) and (2), making use of Router.mount to separate stuff into subrouters:

// NOTE: assumes worktop@next

// file: lib/types.ts
import type { Durable } from 'worktop/cfw.durable';

export type Context = import('worktop').Context & {
  bindings: {
    ASSETS: Durable.Namespace;
  };
}

// file: lib/router.api.ts
import { Router } from 'worktop';
import type { Context } from './types';

export const API = new Router<Context>();

API.add('GET', '/hello', () => new Response('GET /api/hello'));
API.add('GET', '/world', () => new Response('GET /api/world'));

// file: lib/router.main.ts
import { Router } from 'worktop';
import * as cfw from 'worktop/cfw';    
import { API } from './router.api';

import type { Context } from './types';

const MAIN = new Router<Context>();

// All "/api/*" request to API subrouter
MAIN.mount('/api/', API);

// Everything else forward to `env.ASSETS` binding
MAIN.add('GET', '*', (req, context) => {
  return context.bindings.ASSETS.fetch(req);
});

// initialize Module Worker
export default cfw.start(MAIN.run);

from worktop.

lukeed avatar lukeed commented on July 3, 2024

Hey, thanks!

So few approaches

  1. If you know you only want to use worktop for /api/* routes, then you can build off of the snippet you shared:

    import { Router } from 'worktop';
    // NOTE: assumes worktop@next
    
    const API = new Router;
    
    API.add('GET', '/api/hello', async (req, context) => {
      return new Response('Example');
    });
    
    // ...
    
    export default {
      async fetch(req, env, ctx) {
        const url = new URL(req.url);
      
        if (url.pathname.startsWith('/api/')) {
          ctx.bindings = env;
          return API.run(req, ctx);
        }
      
        // do fallback
        return env.ASSETS.fetch(req);
      }
    }
  2. Deploy a Module Worker (via worktop) and define a GET /* route last in your worktop app:

    // NOTE: assumes worktop@next
    import { Router } from 'worktop';
    import * as cfw from 'worktop/cfw';
    
    import type { Context } from 'worktop';
    import type { Durable } from 'worktop/cfw.durable';
    
    interface MyContext extends Context {
      bindings: {
        ASSETS: Durable.Namespace;
      };
    }
    
    const API = new Router<MyContext>();
    
    API.add('GET', '/api/hello', async (req, context) => {
      return new Response('Example');
    });
    
    // ...
    
    API.add('GET', '/*', (req, context) => {
      return context.bindings.ASSETS.fetch(req);
    });
    
    // initialize Module Worker
    export default cfw.start(API.run);
  3. Kinda similar to (2) but you use the onerror hook and if the handler if triggered with a 404 status you pass it off to context.bindings.ASSETS


I'd go with either 1 or 2 personally.

Hope that helps~

from worktop.

vladinator1000 avatar vladinator1000 commented on July 3, 2024

Beautiful, thanks @lukeed. I'll use this as a stepping stone to build a full-stack app with server side rendering. Hoping to open-source it as a template if it works.

By the way, I had a great time using the current version of Worktop to make a back end example that talks to a database ❤️ Keep up the good work, I really appreciate it! https://github.com/vladinator1000/cloudflare-workers-ts-graphql

from worktop.

Related Issues (20)

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.