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

chore: add test for CORS OPTIONS handler #1331

Merged
merged 3 commits into from
May 30, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
11 changes: 9 additions & 2 deletions packages/api/src/utils/logs.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export class Logging {
this.logEventsBatch = []
this.startTs = Date.now()
this.currentTs = this.startTs
this._finished = false

const cf = request.cf
let rCf
Expand Down Expand Up @@ -145,6 +146,12 @@ export class Logging {
* @param {Response} response
*/
async end (response) {
if (this._finished) {
throw new Error(
`end() has already been called on this Logging instance.
You must make a new instance per request.`
)
}
if (this.opts?.debug) {
response.headers.set('Server-Timing', this._timersString())
}
Expand All @@ -171,7 +178,7 @@ export class Logging {
await this.postBatch()
}
this.ctx.waitUntil(run())

this._finished = true
adamalton marked this conversation as resolved.
Show resolved Hide resolved
return response
}

Expand Down Expand Up @@ -276,7 +283,7 @@ export class Logging {
if (!timeObj) {
return console.warn(`No such name ${name}`)
}

this._times.delete(name)
const end = Date.now()
const duration = end - timeObj.start
const value = duration
Expand Down
15 changes: 15 additions & 0 deletions packages/api/test/cors.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,19 @@ describe('CORS', () => {
assert.strictEqual(res.status, 500, 'Expected 500 on /error')
assert.strictEqual(res.headers.get('Access-Control-Allow-Origin'), '*')
})

it('correctly responds to preflight request', async () => {
const res = await fetch(new URL('version', endpoint), {
method: 'OPTIONS',
headers: {
Origin: 'web3.storage',
'Access-Control-Request-Method': 'whatever',
'Access-Control-Request-Headers': 'whatever'
}
})
assert(res.ok)
assert.strictEqual(res.status, 204, 'Expected 204 status for OPTIONS request')
assert.strictEqual(res.headers.get('Access-Control-Allow-Origin'), 'web3.storage')
assert.strictEqual(res.headers.get('Access-Control-Allow-Methods'), 'GET,POST,DELETE,OPTIONS')
})
})