Skip to content

Commit

Permalink
fix: first request on server start should never 304
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed May 12, 2020
1 parent f9b267f commit c8a1ffd
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
11 changes: 10 additions & 1 deletion src/node/server/serverPluginServeStatic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { ServerPlugin } from '.'
const send = require('koa-send')
const debug = require('debug')('vite:history')

export const seenUrls = new Set()

export const serveStaticPlugin: ServerPlugin = ({
root,
app,
Expand Down Expand Up @@ -56,7 +58,14 @@ export const serveStaticPlugin: ServerPlugin = ({
})

if (!config.serviceWorker) {
app.use(require('koa-conditional-get')())
app.use(async (ctx, next) => {
await next()
// the first request to the server should never 304
if (seenUrls.has(ctx.url) && ctx.fresh) {
ctx.status = 304
}
seenUrls.add(ctx.url)
})
}
app.use(require('koa-etag')())

Expand Down
7 changes: 6 additions & 1 deletion src/node/server/serverPluginVue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { Context } from 'koa'
import { transform } from '../esbuildService'
import { InternalResolver } from '../resolver'
import qs from 'querystring'
import { seenUrls } from './serverPluginServeStatic'

const debug = require('debug')('vite:sfc')
const getEtag = require('etag')
Expand Down Expand Up @@ -58,7 +59,11 @@ export const vuePlugin: ServerPlugin = ({
ctx.etag = getEtag(ctx.body)
// only add 304 tag check if not using service worker to cache user code
if (!config.serviceWorker) {
ctx.status = ctx.etag === ctx.get('If-None-Match') ? 304 : 200
ctx.status =
seenUrls.has(ctx.url) && ctx.etag === ctx.get('If-None-Match')
? 304
: 200
seenUrls.add(ctx.url)
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/node/utils/fsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import fs from 'fs-extra'
import LRUCache from 'lru-cache'
import { Context } from 'koa'
import { Readable } from 'stream'
import { seenUrls } from '../server/serverPluginServeStatic'

const getETag = require('etag')

Expand Down Expand Up @@ -36,10 +37,12 @@ export async function cachedRead(
ctx.lastModified = new Date(cached.lastModified)
if (
ctx.__serviceWorker !== true &&
ctx.get('If-None-Match') === ctx.etag
ctx.get('If-None-Match') === ctx.etag &&
seenUrls.has(ctx.url)
) {
ctx.status = 304
}
seenUrls.add(ctx.url)
ctx.body = cached.content
}
return cached.content
Expand Down

0 comments on commit c8a1ffd

Please sign in to comment.