Skip to content

Commit

Permalink
feat: allow for setting CORS values via ENV (#8)
Browse files Browse the repository at this point in the history
* feat: allow for setting CORS values via ENV

* chore: prefer ternary ops

* fix: consistent API
  • Loading branch information
nicosantangelo authored and abarmat committed Mar 12, 2019
1 parent 92bbc07 commit 51c7cfb
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 7 deletions.
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
API_VERSION=
SERVER_PORT=

CORS_ORIGIN=
CORS_METHOD=

SERVER_SECRET=

AWS_ACCESS_KEY=
Expand Down
7 changes: 4 additions & 3 deletions src/common/ExpressApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ export class ExpressApp {
return this
}

useCORS() {
useCORS(origin: string, method: string) {
const cors = function(_: any, res: express.Response, next: Function) {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Request-Method', '*')
res.setHeader('Access-Control-Allow-Origin', origin)
res.setHeader('Access-Control-Request-Method', method)
res.setHeader(
'Access-Control-Allow-Methods',
'OPTIONS, GET, POST, PUT, DELETE'
Expand All @@ -30,6 +30,7 @@ export class ExpressApp {
}
this.app.use(cors)
this.router.all('*', cors)
return this
}

useVersion(version: string = '') {
Expand Down
10 changes: 6 additions & 4 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ const API_VERSION = env.get('API_VERSION', 'v1')

const app = new ExpressApp()

app.useJSON().useVersion(API_VERSION)
const corsOrigin = env.isDevelopment() ? '*' : env.get('CORS_ORIGIN', '')
const corsMethod = env.isDevelopment() ? '*' : env.get('CORS_METHOD', '')

if (env.isDevelopment()) {
app.useCORS()
}
app
.useJSON()
.useVersion(API_VERSION)
.useCORS(corsOrigin, corsMethod)

// Mount routers
new ContestRouter(app).mount()
Expand Down

0 comments on commit 51c7cfb

Please sign in to comment.