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

feat: add worktop/cors module #22

Merged
merged 6 commits into from
Apr 1, 2021
Merged

feat: add worktop/cors module #22

merged 6 commits into from
Apr 1, 2021

Conversation

lukeed
Copy link
Owner

@lukeed lukeed commented Apr 1, 2021

Closes #1

Example Uses

import { Router } from 'worktop';
import * as CORS from 'worktop/cors';
import * as Cache from 'worktop/cache';

const API = new Router();

// Option 1
// Define global CORS handler
API.prepare = CORS.preflight({
  credentials: true,
  maxage: 86400,
  // ... more
});

// Option 2
// Define non-preflight headers globally
API.prepare = function (req, res) {
  CORS.headers(res, {
    credentials: true,
    // (Optional): React to incoming `Origin` header
    origin: req.headers.get('Origin') || 'https://example.com',
    // ... more
  });

  // ... other global logic
};

// Option 3
// Different CORS per "Route Group"
// NOTE: The compose() is TODO
const isDashboardApp = CORS.preflight({ 
  origin: 'https://app.example.com'
});
API.add('GET', '/api/*', compose(isDashboardApp, ...));
API.add('POST', '/api/*', compose(isDashboardApp, ...));
API.add('DELETE', '/api/*', compose(isDashboardApp, ...));
API.add('PUT', '/api/*', compose(isDashboardApp, ...));

// Allow any origin to request "/static/*" URLs
API.add('GET', '/static/*', compose(
  CORS.preflight({ 
    maxage: 86400,
    origin: '*',
  }),
  async (req, res) => {
    // Get the file...
  }
));

// Option 4
// Mutate `CORS` defaults
// ~> call with different settings
CORS.config.methods = ['GET', 'POST', 'PUT'];
CORS.config.headers = ['Content-Type', 'Authorization'];
CORS.config.credentials = true;

API.add('OPTIONS', '/static/*', CORS.preflight());
API.add('GET', '/static/*', async (req, res) => {
  CORS.headers(res); // also uses defaults
  // .. do something
});

Cache.listen(API.run);

Important: The compose utility (#7) is coming next, making per-route/route-group composing much simpler!

Other Changes

  • Adds origin property to all ServerRequest instances.
  • Fixes ServerResponse#setHeader type definition to allow Arrayable<string | number> values.

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.

worktop/cors
1 participant