Skip to content

Commit

Permalink
Abstracted/exposed the allowPreflight method.
Browse files Browse the repository at this point in the history
  • Loading branch information
coreybutler committed Aug 13, 2020
1 parent 202bf73 commit 7266e34
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 11 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const server = app.listen(() => console.log('Server is running.'))
- [allowHeaders('Origin', 'X-Requested-With')](#allowheadersorigin-x-requested-with)
- [allowMethods('GET', 'POST', 'OPTIONS')](#allowmethodsget-post-options)
- [allowOrigins('a.domain.com', 'b.domain.com')](#alloworiginsadomaincom-bdomaincom)
- [allowPreflight()](#allowpreflight)

### [Responses](#Responses)
- [200](#200)
Expand All @@ -65,6 +66,7 @@ const server = app.listen(() => console.log('Server is running.'))
- [applyBaseUrl (req, route = '/' [, forceTLS = false])](#applybaseurl-req-route---forcetls--false)
- [applyRelativeUrl (req, route = '/' [, forceTLS = false])](#applyrelativeurl-req-route---forcetls--false)
- [errorType](#errorType)
- [commonHeaders](#commonHeaders)

## Middleware

Expand Down Expand Up @@ -353,6 +355,11 @@ This can also be applied to all requests:
```javascript
app.use(API.allowOrigins('a.domain.com', 'b.domain.com'))
```
## allowPreflight
This middleware responds to `OPTIONS` requests with a `200 OK` response. This method is useful because it automatically applies the appropriate CORS configurations to support any request headers submitted to the endpoint.
---
## Responses
Expand Down Expand Up @@ -646,3 +653,9 @@ If JSON is needed, set the errorType to `json`.
```javascript
API.errorType = 'json'
```

### commonHeaders

This is an array of the most common request headers used by HTTP clients. This is useful when constructing your own list of CORS headers using the `allowHeaders` method.

Headers include: `Origin`, `X-Requested-With`, `Content-Type`, and `Accept`. This list may be updated from time to time.
35 changes: 26 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,20 @@ const getRandomValues = buf => {
return buf
}

function priv (value) {
return { enumerable: false, writable: true, configurable: false, value }
}

const ERROR_TYPES = new Set(['json', 'text'])
const COMMON_HEADERS = new Set(['Origin', 'X-Requested-With', 'Content-Type', 'Accept'])

class Endpoint {
constructor () {
Object.defineProperty(this, '__errorType', {
enumerable: false,
writable: true,
configurable: false,
value: 'text'
Object.defineProperties(this, {
__errorType: priv('text')
// __allowedMethods: priv(new Set()),
// __allowedHeaders: priv(new Set()),
// __allowedOrigins: priv(new Set())
})

// Add all known HTTP statuses
Expand All @@ -57,13 +64,17 @@ class Endpoint {

set errorType (value) {
value = (value || 'text').trim().toLowerCase()
if (['json', 'text'].indexOf(value) < 0) {
if (!ERROR_TYPES.has(value)) {
value = 'text'
}

this.__errorType = value
}

get commonHeaders () {
return Array.from(COMMON_HEADERS)
}

// Last argument must be a callback.
validateJsonBody () {
let args = Array.from(arguments)
Expand Down Expand Up @@ -273,7 +284,7 @@ class Endpoint {
}

log (req, res, next) {
console.log(chalk.gray(`${(new Date()).toLocaleTimeString()}: `) + Endpoint.color(req.method)(req.method) + chalk.gray(` ${req.url}`))
console.log(chalk.dim(`${(new Date()).toLocaleTimeString()}: `) + Endpoint.color(req.method)(req.method) + chalk.dim(` ${req.url}`))
next()
}

Expand Down Expand Up @@ -351,10 +362,16 @@ class Endpoint {

app.use((req, res, next) => {
this.allowOrigins(host)(req, res)
this.allowHeaders('Origin', 'X-Requested-With', 'Content-Type', 'Accept')(req, res)
this.allowHeaders(...this.commonHeaders)(req, res)
this.allowMethods('GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS')(req, res)

// Support preflight requests
this.allowPreflight(req, res, next)
})
}

allowPreflight () {
return (req, res, next) => {
if (req.method.toUpperCase() === 'OPTIONS') {
if (req.headers['access-control-request-headers']) {
this.allowHeaders(...req.headers['access-control-request-headers'].split(','))(req, res)
Expand All @@ -364,7 +381,7 @@ class Endpoint {
}

next()
})
}
}

allowMethods () {
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@butlerlogic/common-api",
"version": "1.5.2",
"version": "1.5.3",
"description": "An API engineering productivity kit for Express.",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit 7266e34

Please sign in to comment.