Skip to content

Commit

Permalink
fix: always bypass cache when ?write=true
Browse files Browse the repository at this point in the history
The npm CLI makes GET requests with ?write=true in some cases where it's
intending to send an immediate PUT or DELETE.  Always bypass the cache
for such requests, mirroring the behavior of the registry caching
mechanisms.
  • Loading branch information
isaacs committed Feb 14, 2020
1 parent 55d602e commit 83f89f3
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
14 changes: 13 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,13 @@ function regFetch (uri, opts) {
}
}

const parsed = new url.URL(uri)

if (opts.query) {
const q = typeof opts.query === 'string'
? qs.parse(opts.query)
: opts.query

const parsed = new url.URL(uri)
Object.keys(q).forEach(key => {
if (q[key] !== undefined) {
parsed.searchParams.set(key, q[key])
Expand All @@ -87,6 +88,17 @@ function regFetch (uri, opts) {
uri = url.format(parsed)
}

if (parsed.searchParams.get('write') === 'true' && method === 'GET') {
// do not cache, because this GET is fetching a rev that will be
// used for a subsequent PUT or DELETE, so we need to conditionally
// update cache.
opts = opts.concat({
offline: false,
'prefer-offline': false,
'prefer-online': true
})
}

const doFetch = (body) => fetch(uri, {
agent: opts.agent,
algorithms: opts.algorithms,
Expand Down
24 changes: 24 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,30 @@ test('json()', t => {
.then(json => t.deepEqual(json, { hello: 'world' }, 'got json body'))
})

test('query string with ?write=true', t => {
const cache = t.testdir()
const opts = OPTS.concat({ 'prefer-offline': true, cache })
const qsString = opts.concat({ query: { write: 'true' } })
const qsBool = opts.concat({ query: { write: true } })
tnock(t, opts.registry)
.get('/hello?write=true')
.times(6)
.reply(200, { write: 'go for it' })

return fetch.json('/hello?write=true', opts)
.then(res => t.strictSame(res, { write: 'go for it' }))
.then(() => fetch.json('/hello?write=true', opts))
.then(res => t.strictSame(res, { write: 'go for it' }))
.then(() => fetch.json('/hello', qsString))
.then(res => t.strictSame(res, { write: 'go for it' }))
.then(() => fetch.json('/hello', qsString))
.then(res => t.strictSame(res, { write: 'go for it' }))
.then(() => fetch.json('/hello', qsBool))
.then(res => t.strictSame(res, { write: 'go for it' }))
.then(() => fetch.json('/hello', qsBool))
.then(res => t.strictSame(res, { write: 'go for it' }))
})

test('fetch.json.stream()', t => {
tnock(t, OPTS.registry).get('/hello').reply(200, {
a: 1,
Expand Down

0 comments on commit 83f89f3

Please sign in to comment.