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

feat: cache certificate #3642

Merged
merged 3 commits into from Jul 7, 2021
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 28 additions & 2 deletions packages/vite/src/node/server/http.ts
@@ -1,4 +1,4 @@
import fs from 'fs'
import fs, { promises as fsp } from 'fs'
import path from 'path'
import { Server as HttpServer } from 'http'
import { ServerOptions as HttpsServerOptions } from 'https'
Expand Down Expand Up @@ -44,7 +44,7 @@ export async function resolveHttpsConfig(
pfx: readFileIfExists(pfx)
})
if (!httpsOption.key || !httpsOption.cert) {
httpsOption.cert = httpsOption.key = await createCertificate()
httpsOption.cert = httpsOption.key = await getCertificate(config)
}
return httpsOption
}
Expand Down Expand Up @@ -133,3 +133,29 @@ async function createCertificate() {
})
return pems.private + pems.cert
}

async function getCertificate(config: ResolvedConfig) {
if (!config.cacheDir) return await createCertificate()

const cachePath = path.join(config.cacheDir, '_cert.pem')

try {
const [stat, content] = await Promise.all([
fsp.stat(cachePath),
fsp.readFile(cachePath, 'utf8')
])

if (Date.now() - stat.ctime.valueOf() > 30 * 24 * 60 * 60 * 1000) {
throw new Error('cache is outdated.')
}
wmzy marked this conversation as resolved.
Show resolved Hide resolved

return content
} catch (e) {
wmzy marked this conversation as resolved.
Show resolved Hide resolved
const content = await createCertificate()
fsp
.mkdir(config.cacheDir, { recursive: true })
.then(() => fsp.writeFile(cachePath, content))
.catch(() => {})
return content
}
}