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: Added CORS to config #302

Merged
merged 5 commits into from
Aug 10, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions examples/social-network/config/environments/development.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,25 @@
export default {
server: {
cors: {
origin: '*',
enabled: true,

headers: [
'Accept',
'Content-Type'
],

methods: [
'GET',
'POST',
'PATCH',
'DELETE',
'HEAD',
'OPTIONS'
]
}
},

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought it might be useful to show the CORS config in an example project, so I've left this in here for now.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great idea!

logging: {
level: 'DEBUG',
format: 'text',
Expand Down
6 changes: 4 additions & 2 deletions src/packages/application/initialize.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ export default async function initialize<T: Application>(app: T, {
path,
port,
logging,
database
database,
server: serverConfig
}: Application$opts) {
const routes = loader(path, 'routes');
const models = loader(path, 'models');
Expand Down Expand Up @@ -103,7 +104,8 @@ export default async function initialize<T: Application>(app: T, {

const server = new Server({
Copy link
Contributor

@zacharygolba zacharygolba Aug 10, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be beneficial to spread the serverOpts here:

  const server = new Server({
    ...serverOpts,
    router,
    logger
  });

router,
logger
logger,
...serverConfig
});

if (!LUX_CONSOLE) {
Expand Down
5 changes: 5 additions & 0 deletions src/packages/config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ export function createDefaultConfig(): Config {
const isProdENV = NODE_ENV === 'production';

return {
server: {
cors: {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For style purposes let's leave this property on a single line: cors: {},

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On second thought let's make the boolean enabled flag always present.

cors: {
  enabled: false
}

enabled: false
}
},
logging: {
level: isProdENV ? 'INFO' : 'DEBUG',
format: isProdENV ? 'json' : 'text',
Expand Down
2 changes: 2 additions & 0 deletions src/packages/config/interfaces.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// @flow
import type { Logger$config } from '../logger';
import type { Server$config } from '../server';

export type Config = {
logging: Logger$config;
server: Server$config;
};
39 changes: 27 additions & 12 deletions src/packages/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ import { createResponder } from './responder';
import { tryCatchSync } from '../../utils/try-catch';
import validateAccept from './utils/validate-accept';
import validateContentType from './utils/validate-content-type';
import setCORSHeaders from './utils/set-cors-headers';

import type { Writable } from 'stream';
import type { IncomingMessage, Server as HTTPServer } from 'http';

import type { Request } from './request/interfaces';
import type { Response } from './response/interfaces';
import type { Server$opts } from './interfaces';
import type { Server$opts, Server$config } from './interfaces';

/**
* @private
Expand All @@ -26,9 +27,11 @@ class Server {

router: Server$opts.router;

cors: Server$config.cors;

instance: HTTPServer;

constructor({ logger, router }: Server$opts) {
constructor({ logger, router, cors }: Server$opts) {
Object.defineProperties(this, {
router: {
value: router,
Expand All @@ -44,6 +47,13 @@ class Server {
configurable: false
},

cors: {
value: cors,
writable: false,
enumerable: false,
configurable: false
},

instance: {
value: createServer(this.receiveRequest),
writable: false,
Expand All @@ -58,19 +68,22 @@ class Server {
}

initializeRequest(req: IncomingMessage, res: Writable): [Request, Response] {
const { logger, router } = this;
const { logger, router, cors } = this;

req.setEncoding('utf8');

return [
createRequest(req, {
logger,
router
}),
createResponse(res, {
logger
})
];
const response = createResponse(res, {
logger
});

setCORSHeaders(response, cors);

const request = createRequest(req, {
logger,
router
});

return [request, response];
}

validateRequest({ method, headers }: Request): true {
Expand Down Expand Up @@ -122,6 +135,8 @@ export default Server;
export { getDomain } from './request';
export { default as createServerError } from './utils/create-server-error';

export type { Server$config } from './interfaces';

export type {
Request,
Request$params,
Expand Down
13 changes: 12 additions & 1 deletion src/packages/server/interfaces.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,18 @@
import type Logger from '../logger';
import type Router from '../router';

export type Server$opts = {
export type Server$cors = {
Copy link
Contributor

@zacharygolba zacharygolba Aug 10, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good pattern you've got going on here. I think we should keep the actual Server$config as a separate type declaration so we can properly isolate what is user-provided and what is required to internally get passed via the framework.

export type Server$cors = {
  origin?: string;
  enabled: boolean;
  headers?: Array<string>;
  methods?: Array<string>;
};

export type Server$config = {
  cors: Server$cors;
};

export type Server$opts = Server$config & {
  logger: Logger;
  router: Router;
};

P.S we should always put semicolons after a type = declaration. The only instance where this is not necessary would be an interface declaration as it is a statement rather than an expression.

enabled: boolean;
origin?: string;
headers?: Array<string>;
methods?: Array<string>;
};

export type Server$config = {
cors: Server$cors;
};

export type Server$opts = Server$config & {
logger: Logger;
router: Router;
};
Expand Down
26 changes: 26 additions & 0 deletions src/packages/server/utils/set-cors-headers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// @flow
import type { Response } from '../index';
import type { Server$cors } from '../interfaces';

export default function setCORSHeaders(res: Response, {
origin,
methods,
headers,
enabled
}: Server$cors) {
if (!enabled) {
return;
}

if (origin) {
res.setHeader('Access-Control-Allow-Origin', origin);
}

if (methods) {
res.setHeader('Access-Control-Allow-Methods', methods.join());
}

if (headers) {
res.setHeader('Access-Control-Allow-Headers', headers.join());
}
}